【问题标题】:Type of "htmlAttributes" in TextBoxFor and how to add more attributes to itTextBoxFor 中“htmlAttributes”的类型以及如何向其添加更多属性
【发布时间】:2013-02-13 22:21:27
【问题描述】:

我添加了一个扩展方法作为我的 MVC 视图的助手,并希望将另一个属性添加到它已有的任何属性中。这是标准 TextBoxFor 方法的签名(我的,除了我的称为“TextBoxForWithTitle”):

public static MvcHtmlString TextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    Object htmlAttributes
)

最后一个参数 htmlAttributes 看起来像一个名称值对。当我将鼠标悬停在它上面时(在运行时),它的值为“{ class= emailtextbox }”,这是我在 Razor 视图中添加的。如何在我的扩展方法中为此添加另一个名称/值属性?我尝试将其转换为字典,但没有成功。

【问题讨论】:

    标签: asp.net-mvc extension-methods


    【解决方案1】:

    您可以将其作为 RouteValueDictionary 进行访问:

    IDictionary<string, object> newAttributes = new RouteValueDictionary(htmlAttributes);
    

    这允许您在代码中添加新项目:

    newAttributes.Add(new KeyValuePair<string, object>("id", id));
    

    【讨论】:

      【解决方案2】:

      它表明它是对象的类型。如何初始化一个新对象? new { [properties go here] }。所以我们要解决这个问题:

      @Html.TextBoxFor(x => x.SomeId, new { @class = "whatever-class", @id = 5, data_customAttr = "customAttribute"})
      

      请注意,如果您需要data- 属性,请使用_ 而不是-。它们将被转换。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-14
        • 1970-01-01
        • 1970-01-01
        • 2021-09-24
        • 2016-07-28
        • 1970-01-01
        • 1970-01-01
        • 2019-12-25
        相关资源
        最近更新 更多