Search code examples
asp.net-mvcasp.net-mvc-4razorasp.net-web-apirazor-2

How to render view to string in ASP.NET MVC4 Api controller


ASP.NET MVC4 Web API controller should return Razor view as html in json result property.

I tried controller

public class TestController : ApiController
{
    public HttpResponseMessage Get()
    {
        var body = RenderViewToString<object>("~/Views/Broneeri/Schedule.cshtml", new object() );
        return Request.CreateResponse(HttpStatusCode.OK, new { content = body } );
    }

    string RenderViewToString<T>(string viewName, T model)
    {
        ViewDataDictionary ViewData = new ViewDataDictionary(model);
        TempDataDictionary TempData = new TempDataDictionary();
        ControllerContext controllerContext = new System.Web.Mvc.ControllerContext();
        controllerContext.RouteData = new RouteData();

        controllerContext.RouteData.Values.Add("controller", "Schedule");
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
            var viewContext = new ViewContext(controllerContext, viewResult.View, ViewData,          
                       TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }
 }

but I got a strange exception

System.NotImplementedException was unhandled by user code
  HResult=-2147467263
  Message=The method or operation is not implemented.
  Source=System.Web
  StackTrace:
       at System.Web.HttpContextBase.get_Items()
       at System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext, String[] locations, String[] areaLocations, String locationsPropertyName, String name, String controllerName, String cacheKeyPrefix, Boolean useCache, String[]& searchedLocations)
       at System.Web.Mvc.VirtualPathProviderViewEngine.FindPartialView(ControllerContext controllerContext, String partialViewName, Boolean useCache)
       at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths)
       at System.Web.Mvc.ViewEngineCollection.Find(Func`2 cacheLocator, Func`2 locator)
...

at line

var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);

How to return HTML content from view in ASP.NET 4 Web API controller?


Solution

  • You need to Install-Package RazorEngine using your NuGet console. Here is code that worked for me:

    using RazorEngine;
    using RazorEngine.Templating;
    
    string razorTemplate = "Hello @Model!";
    string html = Engine.Razor.RunCompile(
        razorTemplate, 
        "uniqueTemplateKey", // Guid.NewGuid().ToString() for example
        modelType: typeof(string), 
        model: "Lorem Ipsum");
    

    Hope it helps!