创建一个textarea帮助器,将视图内容作为参数

时间:2011-12-17 13:09:17

标签: asp.net-mvc asp.net-mvc-3

我想创建一个html帮助器,它将作为视图的参数内容接收,如下所示:

<% Html.MyTextArea("txt1", () => {%> 

content of the view
<%=Html.TextBox("Name") %>
...
<% }) %>

4 个答案:

答案 0 :(得分:5)

我不确定如何在Web窗体视图引擎中完成它,但请查看此博文:

Templated Razor Delegates

答案 1 :(得分:3)

由于您已将其标记为MVC,我建议您可以执行类似我在my blog上发布的操作,以获取模板的语法突出显示,因为解决方案非常相似,如果您不需要操纵内部内容,只是想以某种方式“包装”它(比如需要一些额外逻辑的包含元素)。

使用该技术,HtmlHelper方法接收块的上下文。语法与您建议的技术略有不同。

例如,您可以使用以下内容:

@using(Html.MyTextArea("txt1")) 
{
  <some HTML content here>
}

将上下文传递给IDisposable对象,该对象包括Writer(用于写入当前输出流)。在那里,它可以输出多个元素或根据需要进行其他操作。 Dispose用于编写一个close元素(如果需要)。

所以,你最终会得到这样的东西:

<textarea><some HTML content here></textarea>

但是,正如我所提到的,这并没有为函数本身提供内部内容。

当Razor页面向内渲染时,没有一种有效的方法可以按照你想要的方式获取输出。有一些posts围绕将Partial的输出缓存到一个字符串(这意味着您的示例中的内部内容将位于另一个文件,.ascx文件中),因此您可能希望查看这些内容。

答案 2 :(得分:3)

一种方法是,

    public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, Action<TextWriter> action)
    {
        var writer = new StringWriter();
        action(writer);
        // here writer contains the html
        return htmlHelper.TextArea(name);
    }

    <%:Html.TextArea("txt1",(writer) => {
        writer.Write("content of the view");
        writer.Write(HttpUtility.HtmlEncode(Html.TextBox("Name")));
    }) %>

答案 3 :(得分:3)

你的意思是这样吗?

namespace System.Web.Mvc {
    public static class HtmlHelperExtensions {
        public static MvcHtmlString MyTextArea(this HtmlHelper htmlHelper, string id, Func<MvcHtmlString> helperFunc) {
            return new MvcHtmlString(string.Format("<div id=\"{0}\">{1}</div>", id, helperFunc()));
        }
    }
}

您可以这样使用:

<%: Html.MyTextArea("txt1", () => Html.TextBox("Name", "abc")) %>