2010-12-07 65 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