Can you make a dynamically typed HtmlHelper extension in Asp.Net MVC 3?
I am attempting to make a dynamically typed extension HtmlHelper, but I am getting and error. For example, if I try this:
public static string DropDownWithAdder<T>(thi开发者_Go百科s HtmlHelper helper)
{
return "Test Worked";
}
And this in the View:
@Html.DropDownWithAdder<Code>()
I get the error
CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'DropDownWithAdder' and no extension method 'DropDownWithAdder' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
But if I simply remove the <T> it works just fine. My question is can you use a generic typing in an Html extension method?
The extension method needs to take the Html helper object as its first parameter
public static string DropDownWithAdder<T>(this HtmlHelper helper)
{
return "Test Worked";
}
Edit:
You also need to surround the call in brackets to prevent Razor interpreting the < as the start of an html tag:
@(Html.DropDownWithAdder())
精彩评论