ASP.NET MVC – Combine Json result with ViewResult

You can also render a PartialViewResult to a string, and then pass this string via JSON to your view, rendering it in your page using jQuery.

You can see that in this post: http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/.

I’ve created an extension to make it easier:

public static class MvcHelpers
{
    public static string RenderPartialView(this Controller controller, string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

        controller.ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}

In my controller I call it as follows:

const string msg = "Item succesfully updated!";
return new JsonResult
           {
               Data = new
                          {
                              success = true, 
                              message = msg,
                              view = this.RenderPartialView("ProductItemForm", model)
                          },
               JsonRequestBehavior = JsonRequestBehavior.AllowGet
           };

Where “this” is the controller in the case, “ProductItemForm” is my view and “model” is my productItem object 🙂

Hope this helps 😉

Leave a Comment

tech