I need to render a partial view as string. For this I use following Helper class:
public static string RenderRazorViewToString(Controller controller, string viewName, object model = null)
{
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
IViewEngine viewEngine =
controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as
ICompositeViewEngine;
ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, false);
ViewContext viewContext = new ViewContext(
controller.ControllerContext,
viewResult.View,
controller.ViewData,
controller.TempData,
sw,
new HtmlHelperOptions()
);
viewResult.View.RenderAsync(viewContext);
return sw.GetStringBuilder().ToString();
}
}
This works but I now need a similiar Method that also accepts a list of parameters. The View I want to render as a string is called by following Controller method:
public Task<IActionResult> IndexPartial(string? searchValue, string? filterValue)
{
IQueryable<Invoice> query
....Manipulate query by searchValue and filterValue
return PartialView("IndexPartial",await query.ToListAsync());
}
When I call Helper.RenderRazorViewToString(controller, "IndexPartial", model) I have to pass the stringValue and FilterValue.
Does Anybody know how to achieve this?
I think you may understand the usage of RenderRazorViewToString.This method is called by the following code:
Helper.RenderRazorViewToString(controller, "PartialViewName", model);
The second parameter is not the method name,it is the partial view name.It would not get to the IndexPartial method.
What you want is to parse the partial view with model to string.The model data get by manipulating query by searchValue and filterValue.
To meet your requirement,what you need do should be like below:
public string IndexPartial(string? searchValue, string? filterValue)
{
var model = _context.Pupils
.Where(a => a.Name.Contains(searchValue)&& a.Email.Contains(filterValue))
.FirstOrDefault(); //Manipulate query by searchValue and filterValue
//pass the correct model to the RenderRazorViewToString method
//then it would render the partial view to the correct string
var data = Helper.RenderRazorViewToString(this, "PartialViewName", model);
return data;
}
Result:

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