7

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 ?

Dave Alperovich
  • 32,320
  • 8
  • 79
  • 101
Patrick
  • 5,442
  • 9
  • 53
  • 104
  • Please correct me if I wrong, you want to generate HTML, then get an Id from this HTML, and at last send both Id and HTML in JSON? – Dima Mar 23 '13 at 15:30
  • Yes and no. The method GetBlogEntries() creates a partial view that i call from various places on the webpage. It does however not print out the ID anywhere. So i need to get it separately. Then send the html and the id to the caller. The javascript on the client will just make sure to only get new blog entries if there are any new ones to get. – Patrick Mar 23 '13 at 15:39

1 Answers1

16

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();
        }
    }
Dave Alperovich
  • 32,320
  • 8
  • 79
  • 101