How to generate a HTML of a given partial view on ASP.NET view engine is known.
But if this functionality is used on razor partial view it does not work, as exception says the partial view does not derive from "UserControl".
How to fix the rendering to support razor partial view?
I need this because I generate emails form this partial views ...
UPDATE:
Code that fails (@mcl):
public string RenderPartialToString(string controlName, object viewData)
{
ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };
viewPage.Url = this.GetUrlHelper();
string fullControlName = "~/Views/Email/" + controlName + ".ascx";
viewPage.ViewData = new ViewDataDictionary(viewData);
viewPage.Controls.Add(viewPage.LoadControl(fullControlName));
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter tw = new HtmlTextWriter(sw))
{
viewPage.RenderControl(tw);
}
}
return sb.ToString();
}
For this go to Solution Explorer then select Views -> Shared Folder -> Right-click -> Add View. Now for the View -> Home -> Index. cshtml. Here I am rendering a Partial View using 4 types, so the index.
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.
RenderPartial function to render Partial View in ASP.Net MVC Razor. The data will be fetched from database using Entity Framework and then the Partial View will be rendered using the @Html. RenderPartial function in ASP.Net MVC Razor.
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.
@Html.Partial("nameOfPartial", Model)
Update
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter()) {
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
Although adequate answers have already been given, I'd like to propose a less verbose solution, that can be used without the helper methods available in an MVC controller class. Using a third party library called "RazorEngine" you can use .Net file IO to get the contents of the razor file and call
string html = Razor.Parse(razorViewContentString, modelObject);
Get the third party library here.
You could also use the RenderView Controller extension
from here
(source)
and use it like this:
public ActionResult Do() {
var html = this.RenderView("index", theModel);
...
}
it works for razor and web-forms viewengines
I saw that someone was wondering how to do it for another controller.
In my case I had all of my email templates in the Views/Email folder, but you could modify this to pass in the controller in which you have views associated for.
public static string RenderViewToString(Controller controller, string viewName, object model)
{
var oldController = controller.RouteData.Values["controller"].ToString();
if (controller.GetType() != typeof(EmailController))
controller.RouteData.Values["controller"] = "Email";
var oldModel = controller.ViewData.Model;
controller.ViewData.Model = model;
try
{
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName,
null);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
//Cleanup
controller.ViewData.Model = oldModel;
controller.RouteData.Values["controller"] = oldController;
return sw.GetStringBuilder().ToString();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
throw ex;
}
}
Essentially what this does is take a controller, such as AccountController and modify it to think it's an EmailController so that the code will look in the Views/Email
folder. It's necessary to do this because the FindView
method doesn't take a straight up path as a parameter, it wants a ControllerContext
.
Once done rendering the string, it returns the AccountController back to its initial state to be used by the Response object.
great code; little hint: if you sometimes have to bypass more data and not only the viewmodel ..
if (model is ViewDataDictionary)
{
controller.ViewData = model as ViewDataDictionary;
} else {
controller.ViewData.Model = model;
}
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