Create using for own helper? like Html.BeginForm

天大地大妈咪最大 提交于 2019-11-28 23:43:35

Sure, it's possible:

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);
    }
}

and then:

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

will yield:

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

I'd also recommend you reading about Templated Razor Delegates.

Yes it is; however, to use Tablehelper.* you would need to subclass the base-view and add a Tablehelper property. Probably easier, though, is to add an extension method to HtmlHelper:

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

which will allow you to write:

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

but this will in turn require various other bits of plumbing (to start the element at BeginTable, and end it in Dispose() on the returned value).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!