ASP.NET MVC partially displays the string returned by JSON

So, I have a ready-made method that works, and I use it throughout the site:

public PartialViewResult GetBlogEntries(int itemsToTake = 5) { ... return PartialView("_BlogPost", model); } 

Now I want to get this from my javascript in JSON form.

 public JsonResult GetBlogPostJson() { var blogEntry = GetBlogEntries(1); var lastEntryId = GetLastBlogEntryId(); return Json(new {Html = blogEntry, LastEntryId = lastEntryId}, JsonRequestBehavior.AllowGet); } 

The idea should look like this:

 $.ajax({ url: '/Blog/GetBlogPostJson', dataType: 'json', success: function (data) { var lastEntryId = data.LastEntryId; var html = data.Html; ... } }); 

The problem is that this, of course, does not create a row, but a PartialViewResult.

The question is, how can I solve PartialViewResult in html that I can send back using JSON?

+7
source share
1 answer

I went through this about 6 months ago. The goal was to use the partial filling of the jquery popup dialog box.

The problem is that the View Engine wants to display them in its own awkward order ...

Try it. LMK, if clarification is required.

  public static string RenderPartialViewToString(Controller thisController, string viewName, object model) { // assign the model of the controller from which this method was called to the instance of the passed controller (a new instance, by the way) thisController.ViewData.Model = model; // initialize a string builder using (StringWriter sw = new StringWriter()) { // find and load the view or partial view, pass it through the controller factory ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(thisController.ControllerContext, viewName); ViewContext viewContext = new ViewContext(thisController.ControllerContext, viewResult.View, thisController.ViewData, thisController.TempData, sw); // render it viewResult.View.Render(viewContext, sw); //return the razorized view/partial-view as a string return sw.ToString(); } } 
+16
source

All Articles