Create using for own helper? like Html.BeginForm

前端 未结 2 1373
抹茶落季
抹茶落季 2020-12-15 10:13

I was wondering, is it possible to create your own helper definition, with a using? such as the following which creates a form:

using (Html.BeginForm(params)         


        
相关标签:
2条回答
  • 2020-12-15 11:03

    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.

    0 讨论(0)
  • 2020-12-15 11:12

    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).

    0 讨论(0)
提交回复
热议问题