为自己的帮手创建使用?像 Html.BeginForm [英] Create using for own helper? like Html.BeginForm

查看:25
本文介绍了为自己的帮手创建使用?像 Html.BeginForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,是否可以使用 using 创建您自己的帮助程序定义?例如以下创建表单的内容:

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

这将在我的视图中输出

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

这可能吗?如果是这样,如何?

Is this possible? if so, how?

谢谢

推荐答案

当然有可能:

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

然后:

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

将产生:

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

我还建议您阅读有关模板化的剃刀代表.

这篇关于为自己的帮手创建使用?像 Html.BeginForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆