John
John

Reputation: 733

Loading of ajax result in layout

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

Upvotes: 0

Views: 862

Answers (2)

Ryan
Ryan

Reputation: 20116

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

Upvotes: 1

ahmeticat
ahmeticat

Reputation: 1939

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

Upvotes: 1

Related Questions