本文介绍了MVC将PartialViewResult渲染为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我编辑了问题,因为我更改了流程,但是它并没有改变任何问题...

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

我正在尝试将PartialViewResult呈现为字符串,我尝试使用此问题 ...,我从该问题中得到了提示

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

代替此

<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

RenderRazorViewToString(PartialViewResult)返回此已损坏"字符串...

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

推荐答案

由于调用的操作,还可能返回 ContentResult/Content 对象.

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.

以下是此解决方案的说明(需要 RenderViewToString 方法):

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

查看:

@Html.Action("GetHtmlAction")

PartialView(HTML内容的来源):

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>

控制器:

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

这篇关于MVC将PartialViewResult渲染为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 01:23
查看更多