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);     } 
                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.
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.
@Zach Yes, It's possible. You can return your html with model.
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.
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); } 
                        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);     }); } 
                        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