MVC render PartialViewResult to string

13,236

Solution 1

It is also possible to return the ContentResult / Content object as a result of the invoked Action.

Then use the returned results within a View.

Here is an illustration of this solution (requires the RenderViewToString method):

View:

@Html.Action("GetHtmlAction")

PartialView (source for html content):

<h1>SomeHeader</h1>
<table class="table table-striped">
    <tbody data-bind="template: { name: 'eventTemplate', foreach: events }">
        <tr>
            <td>Fake Cell</td>
        </tr>
    </tbody>
</table>

Controller:

public ActionResult GetHtmlAction() {
    string htmlContent = RenderRazorViewToString("FakePartialView", null);
    return Content(htmlContent);
}

public string RenderRazorViewToString(string viewName, object model) {
    ViewData.Model = model;
    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();
    }
}

Solution 2

This has been confirmed by Microsoft.

It's a bug in the Asp.NET version that comes with Visual Studio 2013 Preview. It has been fixed in Visual Studio 2013 RC.

Share:
13,236
Nefarion
Author by

Nefarion

Student who likes to code

Updated on June 28, 2022

Comments

  • Nefarion
    Nefarion almost 2 years

    Disclaimer: I edited the question because i changed the process, but it does not change anything of the problem...

    I am trying to get a PartialViewResult rendered to a string, i tried to use the RenderRazorViewToString Method from this question render a view as a string..., i got the hint from this qustion mvc return partial view as json

    My problem is, the string looks like this:

    <$A$><h1>SomeHeader</h1> 
    <table</$A$><$B$> class="table table-striped"</$B$><$C$>> <tbody</$C$><$D$> data-bind="template: { name: 'eventTemplate', foreach: events }"</$D$><$E$>></tbody>
    </table></$E$>
    

    instead of this

    <h1>SomeHeader</h1>
    <table class="table table-striped">
        <tbody data-bind="template: { name: 'eventTemplate', foreach: events }"></tbody>
    </table>
    

    Update:
    The Process looks like this:

    public ActionResult Index(string item, long id)
    {
        var cont = SomePartialView(item, id);
        return View(model: RenderRazorViewToString(cont));
    }
    

    now the View just renders the string like this:

    @Model
    

    The RenderRazorViewToString(PartialViewResult) returns this "crippled" string...