【问题标题】:Loading of ajax result in layout加载ajax导致布局
【发布时间】:2019-03-28 12:35:03
【问题描述】:

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

回应

【问题讨论】:

  • 您是说error 处理程序正在执行,尽管响应状态代码为200
  • @RoryMcCrossan 是的,没错。
  • 我怀疑是这种情况,否则它是 jQuery 中的一个 massive 错误。你确定你看到的是同一个 AJAX 调用的响应吗?您在什么情况下发出此 AJAX 请求?
  • @RoryMcCrossan 是的,我已经交叉检查了。
  • 你的方法返回ActionResult,请更改返回类型,或者更改AJAX方法

标签: jquery asp.net-core


【解决方案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);
  }
});

【讨论】:

    【解决方案2】:

    首先,创建将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)

    【讨论】:

    • 我使用的是 Asp.NET core 2.2,但无法解决命名空间问题。
    • 在以下位置找到核心版本:stackoverflow.com/questions/32558941/…
    • 如果你能相应地编辑你的答案会很棒。
    • 不幸的是,我什至无法让核心版本正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    相关资源
    最近更新 更多