Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Return Partial View as JSON

Is there a way to return an HTML string from rendering a partial as part of a JSON response from MVC?

    public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)     {         if (ModelState.IsValid)         {             if(Request.IsAjaxRequest()                 return PartialView("NotEvil", model);             return View(model)         }         if(Request.IsAjaxRequest())         {             return Json(new { error=true, message = PartialView("Evil",model)});         }         return View(model);     } 
like image 836
Marty Trenouth Avatar asked Jan 19 '11 01:01

Marty Trenouth


People also ask

Can we return partial view in MVC?

In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.

How do you render a partial view inside a view in MVC?

Partial function which renders the Partial View. The name of the View and the object of the CustomerModel class are passed to the @Html. Partial function. In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.

Can we return JSON through ViewResult?

@Zach Yes, It's possible. You can return your html with model.

How do I return partial view in Ajax?

Here is our small controller class. The controller class is just a stub and not doing anything great. It contains a testPartial() function that will return a partial view as a result. Now, let's add one partial view to the testPartial() action.


2 Answers

You can extract the html string from the PartialViewResult object, similar to the answer to this thread:

Render a view as a string

PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.

Using the code from the thread above, you would be able to use:

public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model) {     if (ModelState.IsValid)     {         if(Request.IsAjaxRequest())             return PartialView("NotEvil", model);         return View(model)     }     if(Request.IsAjaxRequest())     {         return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});     }     return View(model); } 
like image 193
cacois Avatar answered Sep 24 '22 02:09

cacois


Instead of RenderViewToString I prefer a approach like

return Json(new { Url = Url.Action("Evil", model) }); 

then you can catch the result in your javascript and do something like

success: function(data) {     $.post(data.Url, function(partial) {          $('#IdOfDivToUpdate').html(partial);     }); } 
like image 42
Manatherin Avatar answered Sep 23 '22 02:09

Manatherin