Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>You can see that in this post: <a href="http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/" rel="noreferrer">http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/</a>.</p> <p>I've created an extension to make it easier:</p> <pre><code>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(); } } } </code></pre> <p>In my controller I call it as follows:</p> <pre><code>const string msg = "Item succesfully updated!"; return new JsonResult { Data = new { success = true, message = msg, view = this.RenderPartialView("ProductItemForm", model) }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; </code></pre> <p>Where "this" is the controller in the case, "ProductItemForm" is my view and "model" is my productItem object :)</p> <p>Hope this helps ;)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload