2011-01-13 16 views
2

我试图使用复制大多数标准HtmlHelpers的语法,其中使用object将Html属性添加到生成的标记。如何在自定义HtmlHelper中使用C#对象?

我想有这样的:

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

我如何访问新对象的钥匙,所以我可以从视图中添加属性?

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

回答

4

内置的帮助程序方法使用RouteValueDictionaryobject转换为字典。他们还接受HTML属性提供两个重载,其中一个接受一个object,并且其中一个接受一个IDictionary<string, object>

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"] 
    ... 
} 
相关问题