Create using for own helper? like Html.BeginForm

此生再无相见时 提交于 2019-12-29 04:45: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)) 
{
}

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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/7928532/create-using-for-own-helper-like-html-beginform

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