I process PartialViews / Models using the method below to send template letters.
I am using the code below to convert the partial and model to an html string that I can pass into the email sending code.
public class BaseController : Controller
{
public string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
throw new ArgumentException("No View Path Provided.");
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();
}
}
}
This currently works in BaseController, I would like to move it to a helper method so that I can move my email model by building / unloading the controller.
The problem is that I do not have access to ViewData / TempData / ControllerContext
I can update the ControllerContext, but I do not know what to do with ViewData / TempData.
This is how I will use what I have in the controller:
//Do Stuff in Controller
var html = RenderPartialViewToString("~/Views/Mail/_ForgotPassword.cshtml", new MailModel { Username = "Skrillex", SomethingElse = "foo" });
//Send the Email
Jason source
share