【问题标题】:How to use a C# object in custom HtmlHelper?如何在自定义 HtmlHelper 中使用 C# 对象?
【发布时间】:2011-01-14 07:59:48
【问题描述】:

我正在尝试复制大多数标准 HtmlHelpers 的语法,其中 object 用于将 Html 属性添加到生成的标签。

我想要类似的东西:

<%: Html.MyCustomHelper("SomeValue", new { id="myID", @class="myClass" })%>

如何访问该新对象的键,以便从视图中添加属性?

这会使用反射吗?我听说过这个词,但我不熟悉。

【问题讨论】:

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


    【解决方案1】:

    内置辅助方法使用RouteValueDictionaryobject 转换为字典。它们还提供了两种接受 HTML 属性的重载,一种接受object,另一种接受IDictionary&lt;string, object&gt;

    public static string MyCustomHelper(this HtmlHelper htmlHelper, string someValue, object htmlAttributes)
    {
        return htmlHelper.MyCustomHelper(someValue, new RouteValueDictionary(htmlAttributes));
    }
    
    public static string MyCustomHelper(this HtmlHelper htmlHelper, string someValue, IDictionary<string, object> htmlAttributes)
    {
        // Get attributes with htmlAttributes["name"]
        ...
    }
    

    【讨论】:

      【解决方案2】:

      此能力由 Eilon Lipton 在 MVC 团队中创建。详细信息在这里 - 并下载提供的代码以自行推出。

      http://weblogs.asp.net/leftslipper/archive/2007/09/24/using-c-3-0-anonymous-types-as-dictionaries.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-05
        • 1970-01-01
        • 2012-01-20
        相关资源
        最近更新 更多