使用自己的助手创建? 喜欢Html.BeginForm

我想知道,是否有可能创建自己的帮助器定义,使用? 例如以下创建表单:

using (Html.BeginForm(params)) { } 

我想做那样的自己的帮手。 这是一个我想做的简单例子

 using(Tablehelper.Begintable(id) { content etc } 

这将在我的视图中输出

 
content etc

这可能吗? 如果是这样,怎么样?

谢谢

当然,这是可能的:

 public static class HtmlExtensions { private class Table : IDisposable { private readonly TextWriter _writer; public Table(TextWriter writer) { _writer = writer; } public void Dispose() { _writer.Write(""); } } public static IDisposable BeginTable(this HtmlHelper html, string id) { var writer = html.ViewContext.Writer; writer.Write(string.Format("", id)); return new Table(writer); } }

然后:

 @using(Html.BeginTable("abc")) { @:content etc } 

会产生:

 
content etc

我还建议你阅读有关模板化剃刀代表的信息 。

是的; 但是,要使用Tablehelper.*您需要对基础视图进行子类化并添加Tablehelper属性。 但是,可能更容易向HtmlHelper添加扩展方法:

 public static SomeType BeginTable(this HtmlHelper html, string id) { ... } 

这将允许你写:

 using (Html.BeginTable(id)) { ... } 

但这又需要各种其他的管道(在BeginTable上启动元素,并在返回的值上以Dispose()结束)。