微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/98940.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐