HuwD
HuwD

Reputation: 1810

Render View as String

Am trying to render a view as a string to be used as an email template. Am currently trying to implement this example: https://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String

However am having difficulty with this section of code:

public ViewRenderer(ControllerContext controllerContext = null)
{
    // Create a known controller from HttpContext if no context is passed
    if (controllerContext == null)
    {
        if (HttpContext.Current != null)
            controllerContext = CreateController<ErrorController>().ControllerContext;
        else
            throw new InvalidOperationException(
                "ViewRenderer must run in the context of an ASP.NET " +
                "Application and requires HttpContext.Current to be present.");
    }
    Context = controllerContext;
}

Visual Studio is giving me the following error:

"The type or namespace name 'ErrorController' could not be found (are you missing a using directive or an assembly reference?)"

Am probably missing something obvious but can't see what it is. Any ideas?

Upvotes: 1

Views: 9157

Answers (1)

monstertjie_za
monstertjie_za

Reputation: 7823

If you need to Render your view as a string, here is an extension method for the controller I wrote.

NB: I will try and find the exact link I used to help me with this, and update my answer when I find it.

Here is another link, describing this method.

This should do the trick:

public static string RenderViewToString(this Controller controller, string viewName, object model)
    {
        var context = controller.ControllerContext;
        if (string.IsNullOrEmpty(viewName))
            viewName = context.RouteData.GetRequiredString("action");

        var viewData = new ViewDataDictionary(model);

        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
            var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }

If you want to call this from a controller, you simply do the following:

var strView = this.RenderViewToString("YourViewName", yourModel);

Upvotes: 7

Related Questions