使用自己的助手创建?喜欢Html.BeginForm

Ron*_*ijm 10 .net c# html-helper razor asp.net-mvc-3

我想知道,是否有可能创建自己的帮助器定义,使用?例如以下创建表单:

using (Html.BeginForm(params)) 
{
}
Run Code Online (Sandbox Code Playgroud)

我想做那样的自己的帮手.这是一个我想做的简单例子

using(Tablehelper.Begintable(id)
{
    <th>content etc<th>
}
Run Code Online (Sandbox Code Playgroud)

这将在我的视图中输出

<table>
  <th>content etc<th>
</table>
Run Code Online (Sandbox Code Playgroud)

这可能吗?如果是这样,怎么样?

谢谢

Dar*_*rov 20

当然,这是可能的:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

@using(Html.BeginTable("abc"))
{
    @:<th>content etc<th>
}
Run Code Online (Sandbox Code Playgroud)

会产生:

<table id="abc">
    <th>content etc<th>
</table>
Run Code Online (Sandbox Code Playgroud)

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