将MVC的PartialViewResult呈现为字符串

3
免责声明:我编辑了问题,因为我更改了过程,但这并不改变问题的任何内容...
我正在尝试将PartialViewResult渲染为字符串,我尝试使用这个问题的RenderRazorViewToString方法render a view as a string...,我从这个问题中得到了提示mvc return partial view as json 我的问题是,该字符串看起来像这样:
<$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>

更新:
流程看起来像这样:
public ActionResult Index(string item, long id)
{
    var cont = SomePartialView(item, id);
    return View(model: RenderRazorViewToString(cont));
}

现在,View只是像这样呈现字符串:

@Model
RenderRazorViewToString(PartialViewResult) 返回这个“残缺”的字符串...

为什么需要将部分内容作为JSON返回?请附上您的使用代码(我假设您是使用JQuery)。 - Dave Alperovich
3个回答

7

也可以将调用的Action返回的ContentResult/Content对象作为结果返回。

然后在视图中使用返回的结果。

以下是使用该解决方案的示例(需要RenderViewToString方法):

视图:

@Html.Action("GetHtmlAction")

局部视图(用于HTML内容的源代码):

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

2
微软已经确认了这个问题。这是 Visual Studio 2013 Preview 自带的 Asp.NET 版本中的一个 bug。在 Visual Studio 2013 RC 中已经修复了此问题。

0

在将字符串转换为json之前,它是什么样子的?它有美元符号吗? 如果您只是创建一个具有所需输出的字符串,例如

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

当将其转换为json时,它是否具有美元符号? 如果没有,那么视图中是否有任何奇怪的字符或行结束符可能会导致美元元素。


我已更新问题,而且"result"字符串是在其"Jsonified"之前被捕获的。 - Nefarion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接