问题
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...
回答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();
}
}
回答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.
回答3:
What does the string look like before you convert it to json? Does it have the dollar elements? What happens if you just make a string with your intended output such as
"<h1>SomeHeader</h1><table class=\"table table-striped\"><tbody data-bind=\"template: { name:'eventTemplate', foreach: events }\"></tbody></table>"
Does that have the dollar signs when converted to json? If not, then does the view have any strange characters or line endings in it that might be causing the dollar elements.
来源:https://stackoverflow.com/questions/17554734/mvc-render-partialviewresult-to-string