TextBoxFor中"htmlAttributes"的类型以及如何向其添加更多属性

bir*_*dus 2 asp.net-mvc extension-methods

我已经添加了一个扩展方法作为我的MVC视图的帮助器,并希望为它已有的任何属性添加另一个属性.这是标准TextBoxFor方法的签名(我的,除了我的称为"TextBoxForWithTitle"):

public static MvcHtmlString TextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    Object htmlAttributes
)
Run Code Online (Sandbox Code Playgroud)

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

Dmi*_*try 5

它表明它是对象的类型.你如何初始化一个新对象?new { [properties go here] }.所以我们归结为:

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

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


Jas*_*kan 5

You can access it as a RouteValueDictionary:

IDictionary<string, object> newAttributes = new RouteValueDictionary(htmlAttributes);
Run Code Online (Sandbox Code Playgroud)

This allows you to add new items in your code:

newAttributes.Add(new KeyValuePair<string, object>("id", id));
Run Code Online (Sandbox Code Playgroud)