0

In the Asp.NET core's layout page, I'm trying to load the result of an AJAX post. Status is OK but comes as an error:

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

Response

enter image description here

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
John
  • 693
  • 1
  • 12
  • 37

2 Answers2

1

Firstly, create the function which parse ActionResult to 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();
  }
}

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

instead of return RedirectToAction(action, "Some", model)

UPDATE : update for .NET Core

Just change return RedirectToAction(action, "Some", model) to view.Render("Some/"+action, model);

ahmeticat
  • 1,899
  • 1
  • 13
  • 28
1

dataType is you telling jQuery what kind of response to expect.

Since you return html instead of json result from server,try to remove the dataType: 'json' in your ajax directly. Refer to 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);
  }
});
Ryan
  • 19,118
  • 10
  • 37
  • 53