像Helper.BeginForm()一样创建MVC3 Razor Helper

Pep*_*dez 22 html-helper razor asp.net-mvc-3

我想创建一个帮助器,我可以像Helper.BeginForm()那样在括号之间添加内容.我不介意为我的助手创建一个Begin,End,但这样做非常简单易行.

基本上我想要做的是在这些标签之间包装内容,以便它们呈现已经格式化

就像是

@using Html.Section("full", "The Title")
{
This is the content for this section
<p>More content</p>
@Html.TextFor("text","label")
etc etc etc
}
Run Code Online (Sandbox Code Playgroud)

参数"full"是该div的css id,"title"是该部分的标题.

除了做我想做的事情之外,还有更好的方法来实现这个目标吗?

提前感谢您的帮助.

Wya*_*att 36

这完全有可能.在MVC中完成此操作的方式是Helper.BeginForm函数必须返回实现的对象IDisposable.

IDisposable接口定义了一个Dispose被调用的方法,该方法在对象被垃圾收集之前调用.

在C#中,using关键字有助于限制对象的范围,并在它离开范围时立即对其进行垃圾收集.因此,使用它IDisposable是很自然的.

您将要实现一个实现的SectionIDisposable.它必须在构造时为部分渲染开放标记,并在处理时渲染关闭标记.例如:

public class MySection : IDisposable {
    protected HtmlHelper _helper;

    public MySection(HtmlHelper helper, string className, string title) {
        _helper = helper;
        _helper.ViewContext.Writer.Write(
            "<div class=\"" + className + "\" title=\"" + title + "\">"
        );
    }

    public void Dispose() {
        _helper.ViewContext.Writer.Write("</div>");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在该类型可用,您可以扩展HtmlHelper.

public static MySection BeginSection(this HtmlHelper self, string className, string title) {
    return new MySection(self, className, title);
}
Run Code Online (Sandbox Code Playgroud)