So i have a finished method that works and i use it all over the website:
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);
}
Idea is to get it like this:
$.ajax({
url: '/Blog/GetBlogPostJson',
dataType: 'json',
success: function (data) {
var lastEntryId = data.LastEntryId;
var html = data.Html;
...
}
});
Problem is that this of course do not produce a string, but a PartialViewResult.
Question is, how can i resolve the PartialViewResult into html that i can send back with JSON ?
I went through this about 6 months ago. Goal was to use a partial to populate a jquery popup dialog.
The problem is the View Engine wants to Render them in it's own awkward order...
Try this. LMK if it needs clarification.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With