Can I return a Json result that contains also a rendered view?
I need it to return the new ID of a submitted form along with its HTML and some other properties.
Also that can be helpful when I need to return two (or more) view results from one action inside a Json object.
Thanks!
Make sure you specify POST type, as ajax method uses GET method by default. MVC Controller: Decorate the Action method with HttpPost verb. This action method will only handle http post request from browser. Ajax submission from the browser will be automatically deserialized to FormData c# class as a poco.
JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format). In this article we will learn about JsonResult by taking scenario to bind view using the JSON Data .
Use JsonResult when you want to return raw JSON data to be consumed by a client (javascript on a web page or a mobile client). Use ActionResult if you want to return a view, redirect etc to be handled by a browser.
Json(Object, JsonRequestBehavior) Creates a JsonResult object that serializes the specified object to JavaScript Object Notation (JSON) format using the specified JSON request behavior.
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 ;)
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