c# – Html Helper,RenderPartial如何工作?如何实现可以从局部视图中引入内容的帮助程序?

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

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

例如:

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

有人知道怎么做吗?

解决方法

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 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()方法.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...