Create using for own helper? like Html.BeginForm

前端 未结 2 1374
抹茶落季
抹茶落季 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("");
            }
        }
    
        public static IDisposable BeginTable(this HtmlHelper html, string id)
        {
            var writer = html.ViewContext.Writer;
            writer.Write(string.Format("", id));
            return new Table(writer);
        }
    }
    

    and then:

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

    will yield:

    content etc

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

    提交回复
    热议问题