I have seen many examples in MVC on how to render a view as a string, but I have been unsuccessful in getting it to work if my view has any parameters.
For example I have written a mail subscription email as a view, I want to call the view with a mailID as a parameter to obtain the subscribers details to send a personalised email.
Say I have a controller called Email and a View inside it called SubscribeMail with a parameter called mid
I am using the below function to send the email. Unfortunately it never receives the mail ID and in debugging mode never hits a breakpoint in the view (assuming based on the parameters being past it never hits the view I wrote), yet the sent email still sends the html inside the view, just never receives the personalised data being passed in the viewbag based on the parameters.
This is the function I currently have:
public static string RenderViewToString(string controllerName, string viewName, object viewData)
{
var context = HttpContext.Current;
var contextBase = new HttpContextWrapper(context);
var routeData = new RouteData();
routeData.Values.Add("controller", controllerName);
var controllerContext = new ControllerContext(contextBase,
routeData,
new EmptyController());
var razorViewEngine = new RazorViewEngine();
var razorViewResult = razorViewEngine.FindView(controllerContext,
viewName,
"",
false);
var writer = new StringWriter();
var viewContext = new ViewContext(controllerContext,
razorViewResult.View,
new ViewDataDictionary(viewData),
new TempDataDictionary(),
writer);
razorViewResult.View.Render(viewContext, writer);
return writer.ToString();
}
Which I am calling with:
RenderViewToString("Email","MailSubscribe",new KeyValuePair<string,int>("mid",newSubscription.MailID))
Here is the controller view I am trying to hit (although debugging never reaches it):
public ActionResult MailSubscribe(int mailId)
{
using (var context = new MyEntities())
{
subMail result = context.subMails.FirstOrDefault(x => x.MailID == mailId);
if (result != null)
{
ViewBag.Name = result.FirstName;
}
}
return View();
}
Any idea how I could improve this as the Email/MailSubscribe view is being hit, but not via the method I made.