在ASP.NET MVC中渲染帮助程序内的视图

时间:2014-02-05 14:18:50

标签: c# asp.net-mvc-4

我有以下视图要呈现它(称为Test.ascx)。

<div class='test'>
  <%=ViewBag.MyTranslation%>
</div>
<div class='link'>
  <a href="<%=Url.Action("MyAction", "MyController", new { id = Model })%>">Link</a>
</div>

由我创建的助手:

public static string GetSomething(List<int> items)
{
   if(items == null || items.Count == 0)
   {
      return string.Empty;
   }

   StringBuilder sb = new StringBuilder();
   // many `if` here

   foreach(var num in items) 
   {
       // here I want to render the partial view and store it into string
   }
}

另一种观点是,我试过

<div class="main">
   // some html text

  // follow rule #11 
  // from http://codeclimber.net.nz/archive/2009/10/27/12-asp.net-mvc-best-practices.aspx

   <%=Html.GetSomething(Model.NumberList)
</div>

我尝试使用此处的http://akinyusufer.blogspot.in/2011/05/razor-render-mvc3-view-render-to-string.html

方法

但它在ViewBag崩溃,为null,Url.ActionUrl为空)。

还有另一个更好的解决方案来将视图渲染到字符串中的字符串吗?

1 个答案:

答案 0 :(得分:1)

尝试使用helper.RenderPartial渲染测试视图:

public static void GetSomething(this HtmlHelper helper, List<int> items)
{
    foreach (var num  in items)
    {
        helper.RenderPartial("Test", num);
    }
}

用法:

<% Html.GetSomething(Model.NumberList); %>

或更改GetSomething以返回MvcHtmlString并合并来自helper.Partial(“Test”,num)调用的结果。

相关问题