这是完全有可能的。在 MVC 中完成此操作的方式如下Helper.BeginForm
是该函数必须返回一个实现了IDisposable
.
The IDisposable界面 http://msdn.microsoft.com/en-us/library/system.idisposable.aspx定义了一个名为Dispose
它在对象被垃圾收集之前调用。
在 C# 中,using
关键字有助于限制对象的范围,并在它离开范围时立即对其进行垃圾收集。所以,使用它与IDisposable
是自然的。
你会想要实现一个Section
实现的类IDisposable
。它必须在构造时呈现您的部分的开放标记,并在处置时呈现关闭标记。例如:
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>");
}
}
现在该类型可用,您可以扩展 HtmlHelper。
public static MySection BeginSection(this HtmlHelper self, string className, string title) {
return new MySection(self, className, title);
}