How to parse a PartialView and return a Html string from ApiController?

1.6k views Asked by At

I need to parse a MVC PartialView then convert it to plain html string and send it as HttpResponseMessage from ApiController.

Searching the web i found RazorEngine and i tried to use it unsuccessfully because it does not support MVC helpers like @Html or @Styles.Render("~/css") consequently was throwing me errors (following RazorEngine statement).

So is there any way to render a partial view from a ApiController?

About RazorEngine

Razor vs. MVC vs. WebPages vs. RazorEngine

There is often a confusion about where Razor sits in this set of technologies. Essentially Razor is the parsing framework that does the work to take your text template and convert it into a compilable class. In terms of MVC and WebPages, they both utilise this parsing engine to convert text templates (view/page files) into executable classes (views/pages). Often we are asked questions such as "Where is @Html, @Url", etc. These are not features provided by Razor itself, but implementation details of the MVC and WebPages frameworks.

RazorEngine is another consumer framework of the Razor parser. We wrap up the instantiation of the Razor parser and provide a common framework for using runtime template processing.

My code:

Func<string, string, object, HttpResponseMessage> renderTemplate = (templatePath, templateName, model) =>
{
    var viewPath = HttpContext.Current.Server.MapPath(templatePath);
    var template = File.ReadAllText(viewPath);

    //Here throws error because it does not support MVC helpers like "@Html"
    var parsedTemplate = Engine.Razor.RunCompile(template, templateName, null, model);

    var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(parsedTemplate) };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
};

I was calling the above function this way but of course it does not work:

renderTemplate(templatePath, "keyName", data);

Thanks!

0

There are 0 answers