Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC render partial view to a string to return with JSON [duplicate]

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 ?

like image 810
Patrick Avatar asked Mar 23 '13 15:03

Patrick


1 Answers

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();
        }
    }
like image 184
Dave Alperovich Avatar answered Oct 15 '22 03:10

Dave Alperovich