将html页面重写为字符串的最有效方法(MVC 3)
本文关键字:方法 有效 MVC html 重写 字符串 | 更新日期: 2023-09-27 18:02:50
我需要有这个html页面重写为字符串:
<h1>Report @ViewData["reviewId"]</h1>
<table width="1000">
@foreach (var group in Model.GroupBy(item => item.Parent_Group_Name))
{
<tr bgcolor="gray">
<td><b>@group.Key</b></td>
</tr>
foreach (var line in group)
{
<tr>
<td><b>@line.Child_Group_Name </b></td>
</tr>
<tr>
<td width="100%"><b>Question:</b> @String.Format("{0}. {1}",line.Question_Order,line.Question_Label)</td>
</tr>
<tr>
<td width="100%"><b>Answer:</b> @line.Question_Answer</td>
</tr>
<tr>
<td valign=right>
<table width="100%" >
<thead bgcolor="BDBDBD">Comments</thead>
@foreach (var comment in line.Comments)
{
<tr>
<td width="100%"><font size="3" color=302F2F>@comment.Comment_Text</font></td>
</tr>
<tr>
<td width="100%"><font size="2" color=302F2F>by @comment.Comment_User...[@comment.Comment_Date.ToShortDateString()] </font></td>
</tr>
}
</table><hr />
</td>
</tr>
}
}
</table>
我在想只是使用字符串生成器来包装所有这些html,有没有更有效或优雅的方式来做到这一点?
我使用的方法是:
public static string RenderPartialToString(Controller controller, string viewName, object model)
{
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
如果您需要HTML代码作为另一个视图中的字符串,您可以使用HtmlHelper.Partial()
方法,因为它返回字符串值。
如果你需要在MVC视图之外那么你需要更复杂的东西,就像这里描述的:http://www.west-wind.com/weblog/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String