Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Html助手RenderPartial是如何工作的?如何实现可以从局部视图引入内容的帮助器?_C#_Asp.net Mvc_Html Helper_Partial Views_Renderpartial - Fatal编程技术网

C# Html助手RenderPartial是如何工作的?如何实现可以从局部视图引入内容的帮助器?

C# Html助手RenderPartial是如何工作的?如何实现可以从局部视图引入内容的帮助器?,c#,asp.net-mvc,html-helper,partial-views,renderpartial,C#,Asp.net Mvc,Html Helper,Partial Views,Renderpartial,当您使用Html.RenderPartialis时,将获取要渲染的视图的名称,并在该位置渲染其内容 我想实现类似的功能。我希望它采用要呈现的视图的名称,以及一些其他变量,并呈现容器中的内容 例如: public static class WindowHelper { public static string Window(this HtmlHelper helper, string name, string viewName) { var sb = new Str

当您使用
Html.RenderPartial
is时,将获取要渲染的视图的名称,并在该位置渲染其内容

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

例如:

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();
    }
}
公共静态类WindowHelper
{
公共静态字符串窗口(此HtmlHelper帮助程序、字符串名称、字符串视图名称)
{
var sb=新的StringBuilder();
某人加上(“”);
//将局部视图的内容添加到字符串生成器。
某人加上(“”);
使某人返回字符串();
}
}

有人知道怎么做吗?

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

比如:

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

希望有帮助,
Dan

渲染部分扩展被编程为直接渲染到响应对象。。。您可以在他们的源代码中看到这一点:

....).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;
公共静态类WindowHelper
{
公共静态无效窗口(此HtmlHelper帮助程序、字符串名称、字符串视图名称)
{
var response=helper.ViewContext.HttpContext.response;
回答。写(“”);
//将局部视图的内容添加到字符串生成器。
helper.RenderPartial(viewName);
回答。写(“”);
}
}

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

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