6

当您使用Html.RenderPartialis 时,将获取您要呈现的视图的名称,并在该位置呈现它的内容。

我想实现类似的东西。我希望它采用您要呈现的视图的名称以及其他一些变量,并在容器中呈现内容..

例如:

public static class WindowHelper
{
    public static string Window(this HtmlHelper helper, string name, string viewName)
    {
        var sb = new StringBuilder();

        sb.Append("<div id='" + name + "_Window' class='window'>");
        //Add the contents of the partial view to the string builder.
        sb.Append("</div>");

        return sb.ToString();
    }
}

有人知道怎么做吗?

4

3 回答 3

8

我们正在 MVC 2 中解决此问题。您将能够调用 Html.Partial() 并以字符串形式获取视图的实际内容。

于 2009-08-16T07:33:04.147 回答
8

RenderPartial 扩展程序被编程为直接呈现到 Response 对象...您可以在它们的源代码中看到这一点:

....).Render(viewContext, this.ViewContext.HttpContext.Response.Output);

这意味着如果你稍微改变你的方法,你可能会完成你想要的。除了将所有内容附加到 StringBuilder 之外,您还可以执行以下操作:

using System.Web.Mvc.Html;

public static class WindowHelper
{
    public static void Window(this HtmlHelper helper, string name, string viewName)
    {
        var response = helper.ViewContext.HttpContext.Response;
        response.Write("<div id='" + name + "_Window' class='window'>");

        //Add the contents of the partial view to the string builder.
        helper.RenderPartial(viewName);

        response.Write("</div>");
    }
}

请注意,包括 System.Web.Mvc.Html 允许您访问 RenderPartial() 方法。

于 2009-08-15T23:20:05.217 回答
0

为什么不创建第二个视图并在其中包含部分视图,将名称作为 ViewData 或模型等传递。

就像是:

<div id='<%= ViewData["Name"] + "_Window"%>' class='window'>
   <% Html.RenderPartial(ViewData["Name"]); %>
</div>

希望有帮助,丹

于 2009-08-15T23:08:07.237 回答