Rendering a view to a string has been asked many times, however my question differs.
The ViewEngineResult.View has a method called Render(ViewContext, TextWriter)
My code works fine if I pass in the controller which houses my email views, however if the action method originated on another controller then I need to be able to modify the ViewContext to look in the EmailControllers views.
I can’t figure out exactly what property the Render method is using to figure out what view folders to look in. Essentially i’m looking to figure that out so I can tell it to look in the Email views folder.
Here’s my code for reference:
public static string RenderPartialViewToString(Controller controller, string viewName, object model)
{
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);
controller.ViewData.Model = oldModel;
return sw.GetStringBuilder().ToString();
}
}
catch (Exception ex)
{
throw ex;
}
}
So to recap, If I pass in the orders controller the FindView looks for my view within the Orders view folder, I need to tell it to look in the Email view folder.
The ViewEngine looks at the
RouteDatato determine what.cshtmlfile to load. Specifically thecontrollerandactionproperties. You could (and probably recommended) pass in the controller name you wish to use but you can see I’ve hard coded it toEmailfor now in the code below.More stuff if you really want to know
Razor has several locations it looks for when trying to determine which view to use.
{0}here is the action (or passed in view name) and{1}is the controller.Same as here except we also have
{2}which is the area.All of these parameters come from the RouteData (unless specifically overwritten via parameter such as
View("viewname"). They’re specificallyaction,controllerandarea. By modifying these values you can alter several ways MVC works. Including determining which controller to use before one is selected. Same with actions and areas.Hope this helps.