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

时间:2011-10-28 11:21:10

标签: c# .net asp.net-mvc-3 razor html-helper

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

using (Html.BeginForm(params)) 
{
}

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

using(Tablehelper.Begintable(id)
{
    <th>content etc<th>
}

将在我的视图中输出

<table>
  <th>content etc<th>
</table>

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

由于

2 个答案:

答案 0 :(得分:19)

当然,这是可能的:

public static class HtmlExtensions
{
    private class Table : IDisposable
    {
        private readonly TextWriter _writer;
        public Table(TextWriter writer)
        {
            _writer = writer;
        }

        public void Dispose()
        {
            _writer.Write("</table>");
        }
    }

    public static IDisposable BeginTable(this HtmlHelper html, string id)
    {
        var writer = html.ViewContext.Writer;
        writer.Write(string.Format("<table id=\"{0}\">", id));
        return new Table(writer);
    }
}

然后:

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

将产生:

<table id="abc">
    <th>content etc<th>
</table>

我还建议您阅读Templated Razor Delegates

答案 1 :(得分:0)

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

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

允许你写:

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

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

相关问题