将html页面重写为字符串(MVC 3)的最有效方法?

时间:2013-03-07 14:30:52

标签: c# html asp.net-mvc asp.net-mvc-3 razor

我需要将此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,是否有更高效或更优雅的方法来实现它?

2 个答案:

答案 0 :(得分:0)

如果您需要将HTML代码作为另一个视图中的字符串,则可以使用HtmlHelper.Partial()方法,因为它返回字符串值。

如果你需要在MVC视图之外,那么你需要更复杂的东西,如下所述:http://www.west-wind.com/weblog/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String

答案 1 :(得分:0)

这是我使用的方法:

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