Nick Nick - 1 year ago 99
C# Question

MVC5 Render View (with parameters) as String

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,
new EmptyController());

var razorViewEngine = new RazorViewEngine();
var razorViewResult = razorViewEngine.FindView(controllerContext,

var writer = new StringWriter();
var viewContext = new ViewContext(controllerContext,
new ViewDataDictionary(viewData),
new TempDataDictionary(),
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.

Answer Source

The point is that RenderViewToString renders a view. It doesn't call an action. I assume what you want to achieve is something like this:

string name = string.Empty;
using (var context = new MyEntities())
    subMail result = context.subMails.FirstOrDefault(x => x.MailID == mailId);
    if (result != null)
        name = result.FirstName;
string output = RenderViewToString("Email","MailSubscribe", new { mailId = mailId, Name = name});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download