We know that we can use @Html.Partial("PartialViewName") to render partial view in view. However, sometimes we need to render the partial view to HTML inside the controller. For example, I have a ChoiceResultsPartial which displays the choices that user has made. I also want to send the results to the email address the user provides. The best way to achieve this is to use the same way as @Html.Partial() to get the HTML and send the HTML as email body.
In order to achieve this, we can use following code:
public string RenderViewToString(string viewName, object model, TempDataDictionary tempData)
{
if (string.IsNullOrEmpty(viewName))
viewName = this.ControllerContext.RouteData.GetRequiredString("action");
var viewData = new ViewDataDictionary(model);
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
var viewContext = new ViewContext(this.ControllerContext, viewResult.View, viewData, tempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
In order to achieve this, we can use following code:
public string RenderViewToString(string viewName, object model, TempDataDictionary tempData)
{
if (string.IsNullOrEmpty(viewName))
viewName = this.ControllerContext.RouteData.GetRequiredString("action");
var viewData = new ViewDataDictionary(model);
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
var viewContext = new ViewContext(this.ControllerContext, viewResult.View, viewData, tempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
Here, the viewName parameter is the name of the partial view; the model object is the model data that will be used by the partial view; the tempData is the TempData dictionary that can be used by the partial view.
If you use this method to generate HTML of partial view from inside controller, you are not able to use ViewBag inside the partial view.
Comments