Controller将原始JSON对象作为视图返回

时间:2016-04-21 12:45:41

标签: javascript c# json ajax asp.net-mvc-partialview

我正在使用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') }
});

其中操作是传递所需数据的控制器方法, contentType processData 都是假的

这个ajax调用工作正常并正确地将调用发送到控制器

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中的局部视图作为对象,而不是呈现partialView和成功,完成,之前的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-----"
}

2 个答案:

答案 0 :(得分:0)

您应该直接使用要序列化的数据调用JsonJson调用将返回JsonResult对象,因此请勿将JsonResult的实例传递给它。如果您确实想直接使用JsonResult,请在没有额外调用Json的情况下将其返回。

同时使用Json参数的JsonRequestBehavior重载。

[HttpPost]
public ActionResult MyCtroller(myViewModel model)
{
    var result = new ActualInstanceOrContainerToBeReturned;
    return Json(result, JsonRequestBehavior.AllowGet);
}

另外我不确定你为什么要在JsonResult中返回视图所以我不会发表评论,除非说可能是糟糕的设计。为了SOC的利益,将数据和视图分开(这包括生成这些项目)。

答案 1 :(得分:0)

我认为您需要更改控制器

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);

    // If you want to render as html partial view

    return PartialView("PartialView.cshtml", searchResult);

    // return Json(result));
}

和Javascript代码

   $.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')
                  $("#YOUR_DIV_ID").html(data);
            },
            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') }
        });