Reputation: 6283
I'm trying to build dropdowns automatically in my project by creating my own Html helper method that takes a "dropdown group" code and automatically builds the Html. However, it needs to do this while fully supporting the model.
My end code needs to look like this.
<%: Html.CodeList(m => m.state, 121) %>
... where "121" is the code group that returns a dictionary of key/value pairs from the database.
Here's what I have for my Html helper method so far.
public static MvcHtmlString CodeList<T, TProp>(this HtmlHelper<T> html, Expression<Func<T, TProp>> expr, int category)
{
Dictionary<int, string> codeList = CodeManager.GetCodeList(category); //returns dictionary of key/values for the dropdown
return html.DropDownListFor(expr, codeList, new Object()); //this line here is the problem
}
I can't figure how what exactly to hand to the DropDownListFor method. I assume that I do return html.DropDownListFor() but I'm missing something obvious. Any help?
Upvotes: 0
Views: 244
Reputation: 1038820
There you go:
public static MvcHtmlString CodeList<T, TProp>(
this HtmlHelper<T> html,
Expression<Func<T, TProp>> expr,
int category
)
{
var codeList = CodeManager.GetCodeList(category);
var selectList = new SelectList(
codeList.Select(item => new SelectListItem {
Value = item.Key.ToString(),
Text = item.Value
}),
"Value",
"Text"
);
return html.DropDownListFor(expr, selectList);
}
Remark: static methods such as CodeManager.GetCodeList
are very bad in terms of unit testing your components in isolation.
Upvotes: 1