Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c# - Create using for own helper? like Html.BeginForm

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

I'd like to make my own helper like that. So a simple example I'd like to do

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

which will output in my view

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

Is this possible? if so, how?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...