【问题标题】:Create using for own helper? like Html.BeginForm为自己的助手创建使用?像 Html.BeginForm
【发布时间】:2011-12-17 05:32:01
【问题描述】:

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

using (Html.BeginForm(params)) 
{
}

我想自己做一个这样的助手。所以我想做一个简单的例子

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

将在我的视图中输出

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

这可能吗?如果有,怎么做?

谢谢

【问题讨论】:

    标签: c# .net asp.net-mvc-3 razor html-helper


    【解决方案1】:

    当然,有可能:

    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>
    

    我还建议您阅读有关 Templated Razor Delegates 的内容。

    【讨论】:

    • 好的,谢谢。由于您在课堂上这样做了,我认为使用常规的@helper Method() 是不可能的?另外,我在哪里放置这个?我尝试将它与其他助手一起放在我的 app_code 文件夹中,但这似乎不起作用。
    • @RonSijm,例如,您可以将此类放在 HtmlExtensions.cs 文件中的 Extensions 文件夹中。只需确保将定义此类的命名空间带入视图的范围,以便您可以访问扩展方法:@using AppName.Extensions
    • 谢谢,这似乎有效。太糟糕了,只是将 using 放在 _layout.cshtml 中不起作用。
    • @RonSijm,您可以将命名空间添加到~/Views/web.config 文件的&lt;namespaces&gt; 部分( ~/web.config)。这样,帮助程序将在您的应用程序中普遍可用。或者简单地将其命名空间更改为System.Web.Mvc.Html,这是定义所有标准助手的位置。
    • 需要注意的一点...您应该覆盖在 Table 类中返回空的 ToString()... .
    【解决方案2】:

    是的,是的;但是,要使用Tablehelper.*,您需要继承基视图并添加Tablehelper 属性。不过,可能更简单的是向HtmlHelper 添加扩展方法:

    public static SomeType BeginTable(this HtmlHelper html, string id) {
        ...
    }
    

    这将允许你写:

    using (Html.BeginTable(id))
    {
        ...
    }
    

    但这反过来又需要其他各种管道(以BeginTable 开始元素,并在返回值上以Dispose() 结束它)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 2013-04-04
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      相关资源
      最近更新 更多