我正在使用 MVC 架构,我有一个 POST 表单作为 Bootstrap Modal,在提交到 AJAX 调用后附加其表单数据
$.ajax({
type: "POST",
url: action,
enctype: "multipart/form-data",
data: dataString,
cache: false,
contentType: contentType,
processData: processData,
beforeSend: function () {
block('#mymodal');
},
success: function (data, status, xhr) { console.log("success ajax"); onAjaxSuccess(xhr, status, '#mymodal') },
error: function (xhr, status) { console.log("error ajax"); onAjaxFailed(xhr, status, error, '#error-div') },
complete: function (xhr, status) { console.log("complete ajax"); onAjaxComplete(xhr, status, '#mymodal', '#alert', '#myModal') }
});
其中 action 是传递所需数据的 Controller 方法,contentType 和 processData 都是 false
这个 ajax 调用工作正常并正确地将调用发送到 Controller
public ActionResult MyCtroller(myViewModel model)
{
//processing stuff
JsonResultObject result = new JsonResultObject();
try
{
//return secess
}
catch (Exception ex)
{
//return error
}
SearchCriteria<MyModel> viewModel = new SearchCriteria<MyModel>();
viewModel.SortExpression = m => m.OrderByDescending(a => a.Date);
SearchResult<MyModel> searchResult = MyModelService.Instance.Search(viewModel);
result.PartialViewHtml = RenderPartialViewToString("PartialView.cshtml", searchResult);
return Json(result));
}
在处理完成并返回页面时,它将结果打印为纯 JSON,并将该 JSON 中的部分 View 作为对象,而不是呈现部分 View 和成功、完成、错误 在之前的 Ajax 调用中没有被调用
{
"IsRedirect": false,
"RedirectUrl": null,
"Success": true,
"AlertMessage": {
"IsAutoHide": false,
"Dissmisable": true,
"ShowIcon": false,
"Message": "success",
"AlertCSS": "alert alert-success",
"AlertType": 3,
"AlertTypeMetronic": "success"
},
"PartialViewHtml":"-----partialView HTML code-----"
}
最佳答案
您应该使用您打算序列化的数据直接调用Json
。 Json
调用将返回一个 JsonResult
对象,因此不要将 JsonResult
的实例传递给它。如果您确实想直接使用 JsonResult
,则无需额外调用 Json
即可返回它。
同时使用 Json
的重载和 JsonRequestBehavior
参数。
[HttpPost]
public ActionResult MyCtroller(myViewModel model)
{
var result = new ActualInstanceOrContainerToBeReturned;
return Json(result, JsonRequestBehavior.AllowGet);
}
此外,我不确定您为什么要在 JsonResult 中返回 View ,所以我不会发表评论,只是说这可能是糟糕的设计。为了 SOC 的利益,将数据和 View 分开(这包括这些项目的生成)。
关于javascript - Controller 返回原始 JSON 对象作为 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36770074/