加载ajax导致布局

时间:2019-03-28 12:35:04

标签: jquery asp.net-core

在Asp.NET核心的布局页面中,我试图加载AJAX发布的结果。状态正常,但出现错误:

_Layout.cshtml

<div id="MainContentDiv">
  @RenderBody()
</div>
$.ajax({
  type: 'POST',
  url: '/Something/LoadView',
  dataType: 'json',
  contentType: 'application/json',
  data: JSON.stringify({ ... }),
  error: function (result) {
    console.log("error");
    console.log(result);
  },
  success: function (result) {
    $("#MainContentDiv").html(result);
  }
[HttpPost]
public ActionResult LoadView([FromBody] NodeData model)
{
  string action= "Index";
  switch(model.NodeType)
  {
    case StringConstants.something:
      action = "GData";
      break;
    // ...
  }  
  return RedirectToAction(action, "Some", model);
}

public PartialViewResult GData(NodeData model)
{
  // ... 
  return PartialView("_GroupsData", group);
} 

响应

enter image description here

2 个答案:

答案 0 :(得分:1)

首先,创建将ActionResult解析为string的函数

public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                             viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                 ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}

return Json(RenderRazorViewToString(action,model), JsonRequestBehavior.AllowGet)

代替return RedirectToAction(action, "Some", model)

更新 :. NET Core的更新

只需将return RedirectToAction(action, "Some", model)更改为view.Render("Some/"+action, model)

答案 1 :(得分:1)

dataType是您告诉jQuery期望什么样的响应。

由于您从服务器返回了html而不是json结果,请尝试直接删除ajax中的dataType: 'json'。请参阅ajax dataType

$.ajax({
  type: 'POST',
  url: '/Something/LoadView',
  //dataType: 'json',
  contentType: 'application/json',
  data: JSON.stringify({ ... }),
  error: function (result) {
    console.log("error");
    console.log(result);
  },
  success: function (result) {
    $("#MainContentDiv").html(result);
  }
});