How to use a C# object in custom HtmlHelper?
I am trying to use replicate the syntax for most of the standard HtmlHelpers where an object
is used to add Html attributes to a generated tag.
I would 开发者_如何学Pythonlike to have something like:
<%: Html.MyCustomHelper("SomeValue", new { id="myID", @class="myClass" })%>
How do I access the keys of that new object so I can add attributes from the view?
Would this use reflection? I've heard that word thrown around a bit, but I'm not familiar with it.
The built-in helper methods use RouteValueDictionary
to convert the object
into a dictionary. They also provide two overloads for accepting HTML attributes, one which accepts an object
, and one which accepts an 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"]
...
}
This ability was created by Eilon Lipton on the MVC Team. Details are here - and download the provided code to roll your own.
http://weblogs.asp.net/leftslipper/archive/2007/09/24/using-c-3-0-anonymous-types-as-dictionaries.aspx
精彩评论