首頁 工作上常用到的語法
文章
Cancel

工作上常用到的語法

語法懶人包 讓我可以快速複製貼上

前端

取得DataTables的資料

1
2
3
$("#grid-prodapplymhq").DataTable().rows({ selected: true }).data().toArray();

$("#grid-prodapplymhq").DataTable().rows().data().toArray();

修正單身DataTable時間格式的寫法

1
2
3
4
5
6
7
8
9
{
     "title": "日期",
     "data" : "DATE",
     "defaultContent": "",
     "render": function (data) {
	     var result = formatDate(data, '/');
	     return result;
     }
},

修正單身DataTable超連結

1
2
3
4
5
6
7
8
9
{
    "data": "PAY_CLASS_NAME",
    "defaultContent": "",
    "title": "支付類別",
    "render": function (data, type, full, meta) {
    let temp = navigateToAction(false, "@controllerName", "Edit", { id: full.PAY_CLASS_MANTAINID },full.PAY_CLASS_NAME);
    return temp;
    }
},

修正單頭HTML時間的格式

1
@Html.TextBoxFor(a=>a.START_DATE, "{0:yyyy/MM/dd}",new{,@class="form-control",@autocomplete = "off"})

單頭開始結束時間的格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div class="col-md-6">
	<div style="width:100%;float:left;">
		<label for="" class="form-label">日期</label>
	</div>
	<div class="col-md-1" style="float:left;">
		(起)
	</div>
	<div class="col-md-4" style="float:left;">
		@Html.TextBoxFor(a => a.DATE_START, new { @class = "form-control selectTime queryItem", @autocomplete = "off", maxlength = "10" })
	</div>
	<div class="col-md-1" style="float:left;">
		(迄)
	</div>
	<div class="col-md-4" style="float:left;margin-right:5px;">
		@Html.TextBoxFor(a=>a.DATE_END,new { @class="form-control selectTime queryItem", @autocomplete = "off", maxlength="10" })
	</div>
</div>

AJAX

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    function save() {
        var input = GetInputData();
        $.ajax({
            url: '@Url.Action("Save", '@controllerName')',
            type: "post",
            data: input,
            success:async function (result) {
                if (result.status != null && result.status == false) {
                    await CheckValidationShowResult(result.data, '@controllerName');
                }
                else if (result != null) {
                    copyString(result.desc, '@controllerName',true);
                }
            },
        });
    }

  function GetInputData() {
     var input = { EditType: $("#EditType").val() };
     var mainData = getQuery("editItem", "dataM_");
     var dataList = $('#grid-dataD').DataTable().data().toArray();
     input["dataM"] = mainData;
     input["dataList"] = dataList;
     return input;
 }

儲存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 /// <summary>
 /// 儲存
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 [HttpPost]
 public IActionResult Save(EditViewModel model)
 {
     try
     {
         SetExtendValidation(model);
         if (!CheckValidation(out dynamic errObj))
         {
             return Json(new
             {
                 status = false,
                 data = errObj,
             });
         }
         string result = string.Empty;
         if (model.EditType == EditType.Add)
         {
             result = Insert(model);
         }
         else
         {
             result = Update(model);
         }
         var resp = JsonConvert.DeserializeObject<QueryResponse>(result);
         if (resp.status == responseStatus.error)
         {
             return Json(new { status = false, data = resp.desc });
         }
         return Json(new { status = true, data = resp.desc });
     }
     catch (Exception e)
     {
         _logger.Error(e.Message);
         return Json(new { status = false, data = "" });
     }
 }
 public void SetExtendValidation(EditViewModel model)
 {
     foreach (var item in model.Master)
     {
         ModelState.AddModelError($"MAXQTYY_{i}", $"MSG");
         i++;
     }
 }

後端

查詢

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
[HttpPost]
public async Task<IActionResult> GetMaster()
{
	try
	{
        var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
        var userId = User.Claims.FirstOrDefault(a => a.Type == "AccountID").Value;
        GetRequest<QuerySearchModel>(_apiSettings.Token, Request.Form, out QuerySearchModel searchModel);
		    searchModel.user_Id = userId;
        var req = new SharedQueryRequest<QuerySearchModel>
        {
            authKey = _apiSettings.Token,
            pageIndex = searchModel.pageIndex,
            pageSize = searchModel.pageSize,
            Data = searchModel
        };
        var httpHelper = new HttpHelper();
        var result = _httpHelper.Send(_apiSettings.Url + "/SYSW330/SYSW33001", HttpMethod.Post, JsonConvert.SerializeObject(req));
		var resp = JsonConvert.DeserializeObject<SharedQueryResponse<IEnumerable<ProdInspecMModelz>>>(result);
		if (resp != null && resp.status == responseStatus.success)
		{
			if(resp.Data != null)
			{
				foreach (var d in resp.Data)
				{
					d._PI_NO = EncryptHelper.EncryptionStr4Uni(d.PI_NO);
				}
			}
			return Json(new { draw, recordsFiltered = resp.TotalCount, resp.TotalCount, data = resp.Data });
		}
		else
		{
			return BadRequest();
		}
	}
	catch (Exception e)
	{
		_logger.Error(e.Message);
		return Json(ControllerContext.ActionDescriptor.ActionName + " Error");
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/// <summary>
///  取得query 
/// </summary>
/// <param name="request">Input Request</param>
/// <remarks>
///  取得query 
/// </remarks>
/// <returns></returns>
/// <response code="200">完成</response>
/// <response code="400">參數不完整</response>
/// <response code="401">未授權</response>
/// <response code="500">發生錯誤</response>
[HttpPost("SYSW33001")]
[Produces("application/json")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public ActionResult<SharedQueryResponse> SYSW33001(SharedQueryRequest<QuerySearchModel> request)
{
    _logger.Info($"Input Request:{JsonConvert.SerializeObject(request)}");
    var resp = new SharedQueryResponse<IEnumerable<ProdInspecMModelz>>();

    try
    {
        if (!_authService.isVerfiy(request.authKey)) return Unauthorized();

        int cnts = _prodOrderMDao.SYSW33001(request.Data);
        var dataList = _prodOrderMDao.SYSW33001(request.Data, request.pageIndex, request.pageSize);

        resp.Data = dataList.Data.ToList();
        resp.TotalCount = cnts;
        resp.status = responseStatus.success;
        resp.desc = "OK";

        return Content(JsonConvert.SerializeObject(resp), "application/json");
    }
    catch (Exception ex)
    {
        _logger.Error(ex.Message);
        resp.status = responseStatus.error;
        resp.desc = ex.ToString();
        return Content(JsonConvert.SerializeObject(resp), "application/json");
    }
}


class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public SharedQueryResponse<IEnumerable<ProdInspecMModelz>> SYSW33001(QuerySearchModel request, int pageIndex, int pageSize)
{
    var resp = new SharedQueryResponse<IEnumerable<ProdInspecMModelz>>();
    DynamicParameters param = new DynamicParameters();
    string sqlCmd = SYSW33001_SearchSqlCmd(ref param, request);
    sqlCmd = $"with queryData as ({sqlCmd}) select * from queryData WHERE rn > :pageIndex * :pageSize and rn <= ( :pageIndex + 1 ) * :pageSize ";
    param.Add(":pageIndex", pageIndex);
    param.Add(":pageSize", pageSize);

    using (var conn = Connection)
    {
        conn.Open();
        resp.Data = conn.Query<ProdInspecMModelz>(sqlCmd, param).ToList();
    }
    return resp;
}
public int SYSW33001(QuerySearchModel request)
{
    int result = 0;
    DynamicParameters param = new DynamicParameters();
    string sqlCmd = SYSW33001_SearchSqlCmd(ref param, request);
    sqlCmd = $"with queryData as ({sqlCmd}) select count(*) from queryData ";
    using (var conn = Connection)
    {
        conn.Open();
        result = conn.QueryFirstOrDefault<int>(sqlCmd, param);
    }

    return result;
}
private string SYSW33001_SearchSqlCmd(ref DynamicParameters param, QuerySearchModel req)
{
    string sqlCmd = @$"       
SELECT 
ROW_NUMBER()OVER( ORDER BY A1.BTIME) RN,
A1. *
from test A1
    ";
    param.Add(":user_Id", $"{req.user_Id}");

    if (!string.IsNullOrWhiteSpace(req.PI_USER))
    {
        param.Add(":pi_user", $"{req.PI_USER}");
        sqlCmd += " AND PI_USER = :pi_user ";
    }
   
    sqlCmd += " ";
    return sqlCmd;
}

資料庫操作

Dapper extensions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public BaseResponse Approve()
{
	BaseResponse result = new BaseResponse(){ status = responseStatus.success};
	using (var conn = Connection)
	{
		conn.Open();
		using (var tran = conn.BeginTransaction())
		{
			try
			{
				List<BaseResponse> responses = new List<BaseResponse>();
				//responses.Add(BatchUpdate<PRICE_CHG>(model, conn, new string[] { "", "", "" }, true, tran));
				//responses.Add(BatchUpdate<PRICE_CHG_TEMP>(temp_model, conn, new string[] { "","", "", "" }, true, tran));
				if (responses.Any(x => x.status == responseStatus.error))
				{
					var resp = responses.Where(x => x.status == responseStatus.error).FirstOrDefault();
					tran.Rollback();
					result.status = responseStatus.error;
					result.desc = $"審核失敗";
				}
				else
				{
					tran.Commit();
					result.status = responseStatus.success;
					result.desc = $"單號:{model.FirstOrDefault()?.PC_NO},審核成功";
				}

			}
			catch (Exception ex)
			{
				result.desc = ex.Message;
				result.status = responseStatus.error;
				tran.Rollback();
			}
			finally
			{
				tran.Dispose();
				conn.Close();
				conn.Dispose();
			}
		}
	}
    return result;
}

Dapper extensions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public BaseResponse Approve(DbConnection conn, IDbTransaction tran)
{
	BaseResponse result = new BaseResponse(){ status = responseStatus.success};
	List<BaseResponse> responses = new List<BaseResponse>();
	//responses.Add(BatchUpdate<PRICE_CHG>(model, conn, new string[] { "", "", "" }, true, tran));
	//responses.Add(BatchUpdate<PRICE_CHG_TEMP>(temp_model, conn, new string[] { "","", "", "" }, true, tran));
	if (responses.Any(x => x.status == responseStatus.error))
	{
		var resp = responses.Where(x => x.status == responseStatus.error).FirstOrDefault();
		tran.Rollback();
		result.status = responseStatus.error;
		result.desc = $"審核失敗";
	}
	else
	{
		tran.Commit();
		result.status = responseStatus.success;
		result.desc = $"單號:{model.FirstOrDefault()?.PC_NO},審核成功";
	}
    return result;
}

Dapper SQL

1
2
3
4
5
6
7
8
9
10
private BaseResponse checkExcutPermissions(IDbConnection conn,IDbTransaction tran, string PS_NO)
{
    BaseResponse baseResponse = new BaseResponse { status = responseStatus.success };
    string sqlCmd = @" select * from test D where   D.PS_NO= :PS_NO ";
    DynamicParameters dynamicParameters1 = new DynamicParameters();
    dynamicParameters1.Add(":PS_NO", PS_NO);

    PROD_SHIFT_Mz Entity = conn.QueryFirstOrDefault<PROD_SHIFT_Mz>(sqlCmd, dynamicParameters1, tran);
    return baseResponse;
}
本文由作者按照 CC BY 4.0 進行授權