如何在 ASP.NET MVC 中使用 javascript, jQuery, Ajax 來豐富互動與呈現 (AjaxHelper)
2020-06-23
筆記關於如何在 ASP.NET MVC 中使用 javascript
, jQuery
,增進互動視覺效果的體驗。
jQuery
使用 Ajax 呼叫 Action 來局部更新 View
可以用來與 Boostrap Modal 搭配使用,點選按鈕時即時將資料載入 Modal Content 中並顯示。需要先以 Nuget 安裝 Microsoft.jQuery.Unobtrusive.Ajax,並引用 Scripts/jquery.unobtrusive-ajax.js。
/View
<div class="container">
@Ajax.ActionLink(
"link", "ActionName", "ControllerName", new { id = 0},
new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "elementID",
InsertionMode = InsertionMode.Replace
},
new {@class = "btn btn-primary", style = "margin-right: 5px"}
)
</div>
<div id="elementID"></div>
@section scripts{
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
}
/Controller
public ActionResult AskResponse()
{
return PartialView("~/Views/Partial/_Hello.cshtml");
}
Ajax Loading Effect
搭配 Ajax Loading 效果,讀取前先清空資料,讀取中顯示 icon。
<div class="col-md-12">
@Ajax.ActionLink("載入資料", "GetData", "Home", null,
new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "DataPanel",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "loading",
OnBegin = "new function(){document.getElementById('DataPanel').innerHTML=''}"
}
,new { @class = "btn btn-info mb-3" }
)
<div id="loading" style="display: none">
<img src="~/Content/images/loading.gif" />
</div>
<div id="DataPanel"></div>
</div>
public PartialViewResult GetData()
{
return View(db.Data.ToList());
}
Unobtrusive jQueryval
- 加入section scripts
@section scripts{
@Scripts.Render("~/bundles/jqueryval")
}
- 加入Html Helper, input 必須使用helper 否則必須自打data-val
@Html.ValidationMessageFor(model => model.FacetItem.FacetOrder)
- 一併顯示使用
@Html.ValidationSummary()
AjaxHelper BeginForm
@using (Ajax.BegingForm("ActionName",
new AjaxOptions{
HttpMethod = "GET",
UpdateTargetId = "divMessage",
InsertionMode = InsertionMode.Replace
})) {
<input type="text" name="routeValue" value="value" />
<input type="submit" />
}
後端回傳 Json 匿名類型清單示例 (Action Return Anonymous Class List in Json Format)
public JsonResult GetJson()
{
var empList = new[] { new { empName = "", empId = "" } }.ToList();
foreach (var emp in db.Wtp_Employee)
{
if (emp.Title == "Manager")
{
empList.Add( new { empName = emp.EmployeeName, empId = emp.EmployeeId } );
}
}
return Json(empList.Skip(1), JsonRequestBehavior.AllowGet);
}
使用 Ajax Helper 呼叫 Controller Action 取得回應的 Json 資料 (Fetch Json Data From Controller/Action by Ajax Helper)
/Controller
public ActionResult JsonData(string id, string name){
var data = new {empId = id, EmpName = name, Age = 25};
return Json(data, JsonRequestBehavior.AllowGet);
}
// [GET] ~/home/jsondata/100?name=marry
public ActionResult JsonData(string id, string name)
{
if (Request.IsAjaxRequest()){
var data = new {empId = id, EmpName = name, Age =25};
return Json(data, JsonRequestBehavior.AllowGet);
}
return View();
}
/View
$(function(){
$("#button1").click(function(){
$.ajax({
type: "GET",
url: "JsonData",
data: "id=1&name=mary",
success: function(data) { //data用於接住回傳值
console.log(data);
$("#result").text(data.EmpName);
}
});
});
});
Plugins & Packages
Confirm Delete Alert With SweetAlert2
以下範例結合 SweetAlert2 與 Ajax
$('#closeCase').click(function () {
var caseId = $(this).attr("data-closeId");
swal({
title: '您確定要結案嗎?',
text: " 確定結案後便無法再作意見編輯與檔案上傳",
type: 'question',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
cancelButtonColor: '#aaa',
confirmButtonText: '確認結案',
cancelButtonText: '取消',
allowEnterKey: false
}).then(function () {
$.ajax({
url: "@Url.Action("Close", "Do", null)",
type: "POST",
data: {
id: caseId
},
dataType: "Json",
success: function (data) {
swal("結案", "結案完成!", "success");
toDetach.remove();
},
error: function (xhr, ajaxOptions, thrownError) {
swal("結案過程發生錯誤!", "請稍後再次執行", "error");
}
}); // end of ajax
}); // end of then
}); // end of jQuery