【问题标题】:Controller returns raw JSON object as view控制器返回原始 JSON 对象作为视图
【发布时间】:2016-04-21 12:45:40
【问题描述】:

我正在使用 MVC 架构,我有一个 POST 表单作为引导模式,它在提交到 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 是传递所需数据的控制器方法,contentTypeprocessData 都是 false

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

处理完成后,是时候返回页面了> 在前面的 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-----"
}

【问题讨论】:

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


    【解决方案1】:

    您应该使用要序列化的数据直接调用JsonJson 调用将返回一个JsonResult 对象,因此不要将JsonResult 的实例传递给它。如果您确实想直接使用JsonResult,则无需额外调用Json 即可返回。

    还将Json 的重载与JsonRequestBehavior 参数一起使用。

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

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

    【讨论】:

      【解决方案2】:

      我认为您需要更改控制器

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

      【讨论】:

        猜你喜欢
        • 2016-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多