MVC render PartialViewResult to string

Nefarion picture Nefarion · Jul 9, 2013 · Viewed 12.7k times · Source

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...

Answer

Mikhail picture Mikhail · Jul 18, 2013

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();
    }
}