2010-12-07 30 views
0

我想通过创建自己的Html帮助器方法来自动在我的项目中构建下拉列表,该方法需要一个“下拉组”代码并自动生成Html。但是,它需要完全支持该模型。在ASP.NET MVC2中的自定义DropdownFor

我的结束代码需要看起来像这样。

<%: Html.CodeList(m => m.state, 121) %> 

...其中“121”是从数据库返回键/值对的字典的代码组。

下面是我的Html帮助器方法到目前为止。

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 
    } 

我无法确切地知道如何处理DropDownListFor方法。我假设我返回html.DropDownListFor()但我错过了一些明显的东西。任何帮助?

回答

1

你去那里:

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); 
} 

注:静态方法如CodeManager.GetCodeList是非常糟糕的单元隔离测试您的组件方面。

+0

你会如何建议我分开“GetCodeList”,而不必每次我想要下拉时自己调用它? – 2010-12-08 00:26:41

相关问题