I am writing an ASP.NET Core 6 MVC application.
I have a method in a controller that I need to retrieve a Json value like this
a boolean and a Partial View with the model class
return Json(new { success = true, PartialView("SearchResult", resultViewModel) });
I found this article that says to retrieve PartialView as string. [here][1]
like this
return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
I dont have RenderViewToString
function. Searching.. I found this
protected string RenderViewAsString( string viewName, object model)
{
viewName = viewName ?? ControllerContext.ActionDescriptor.ActionName;
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
IView view = _viewEngine.FindView(ControllerContext, viewName, true).View;
if(view!=null)
{
ViewContext viewContext = new ViewContext(ControllerContext, view, ViewData, TempData, sw, new HtmlHelperOptions());
view.RenderAsync(viewContext).Wait();
}
return sw.GetStringBuilder().ToString();
}
}
From Jquery I have this
success: function (result) {
$("#dvBody").html(result.url);
},
the problem is that it returns a View
instead of a PartialView
Is there a way I can make it return a PartialView?
thanks
[1]: MVC Return Partial View as JSON
2
Answers
I replace this function
for this one
I think there is problem in this line
Try to add below in your PartialView:
result:
My demo like below:
ajax success function: