4

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?

3
  • WebAPI was meant for REST style operations. If you are returning HTML, why not just use a normal controller action and a partial view? Commented Nov 10, 2014 at 11:59
  • WebAPI method returns json data. One property of this data contains response data html format. This content is added to page as html to avoid full page refresh. Thus I need to generate html from WebAPI Commented Nov 10, 2014 at 19:40
  • I posted related question in stackoverflow.com/questions/26854342/… This contains answer which does not work in Mono Commented Nov 10, 2014 at 22:45

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

NuGet package RazorEngine does not belong to Mircrosoft and is not a part of ASP.NET. Although this answer should work for rendering a Razor view into a string, I think this should still be mentioned.
@Dimskiy Do you know if there is a similar package from Microsoft to be used inside a .NET Core Api ?
@bbrinck I'm using RazorLight these days. It's not great but gets the job done...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.