[asp.net mvc][jQuery]透過 ajax的post方法取得json資料回到前端畫面上範例
javascript:
$('div.modal-content').block({
css: { backgroundColor: '0', border: 'none' },
message: '<h1><span class="badge badge-secondary">請稍候...</span></h1>'
});
var rootPath = '@Url.Content("~/")';
$.ajax({
type: 'POST',
//這是傳遞單一參數的方式
url: rootPath + 'MyController/MyAction?caseId=' + $("#CaseId").val(),
//這是傳遞整個物件的方式1
//url: rootPath + 'MyController/MyAction',
//data: $("#EditForm").serialize(),
//這是傳遞整個物件的方式2
//url: rootPath + 'MyController/MyAction',
//data: '{txtContent: "' + $("input[id*=txtTest]").val() + '" }',
//這是回傳多筆JSON資料的情況
success: function (data) {
$('div.modal-content').unblock();
alert(888);
$.each(data, function (i, obj) {
alert(obj.FieldNo);
});
},
//這是回傳單筆JSON資料的情況
// success: function (data) {
// $('div.modal-content').unblock();
// alert(data.idno);
// },
error: function (error) {
alert(error.responseText);
}
});
Controller:
[HttpPost]
//這是接收單一參數string caseId的方式
public ActionResult CaseIdChange(string caseId)
//這是接收整個物件當成參數的方式
//public ActionResult CaseIdChange(MyEditModel model)
{
if(string.IsNullOrEmpty(caseId))
{
return Json(new EmptyResult());
}
// if(model == null)
// {
// return Json(new EmptyResult());
// }
EntryCheckDAL dal = new EntryCheckDAL();
var results = dal.GetCaseInfo(Convert.ToInt16(caseId));
return Json(results);
}
Db access class:
public List<MyModel> GetCaseInfo(int caseId)
{
var caseList = (from c in db.tblCase
where c.CaseId == caseId
select new MyModel
{
column1 = "value1",
column2 = "value2"
}).ToList();
return caseList;
}
參考資料:
Return JSON from MVC via AJAX
https://stackoverflow.com/questions/24412199/return-json-from-mvc-via-ajax