2011-03-30 29 views
3

有一種簡單的方法來消除,使用魔法字符串創建時的SelectList,就像這個例子:使用的SelectList不用魔法串

@Html.DropDownListFor(model => model.FooValue, new SelectList(Model.FooCollection, "FooId", "FooText", Model.FooValue)) 

神奇的字符串是"FooId""FooText"

休息的例子定義如下:

//Foo Class 
public class Foo { 

    public int FooId { get; set; } 
    public string FooText { get; set; } 

}  

// Repository 
public class MsSqlFooRepository : IFooRepository { 

    public IEnumerable<Foo> GetFooCollection() { 

    // Some database query 

    } 

} 

//View model 
public class FooListViewModel { 

    public string FooValue { get; set; } 
    public IEnumerable<Foo> FooCollection { get; set; } 

} 

//Controller 
public class FooListController : Controller { 

    private readonly IFooRepository _fooRepository; 

    public FooListController() { 

    _fooRepository = new FooRepository(); 

    } 

    public ActionResult FooList() { 

    FooListViewModel fooListViewModel = new FooListViewModel(); 

    FooListViewModel.FooCollection = _fooRepository.GetFooCollection; 

    return View(FooListViewModel); 

    } 

} 

回答

0

我使用查看模型,所以我有我的FooValues下拉列表的以下屬性:

public SelectList FooValues { get; set; } 
public string FooValue { get; set; } 

,然後在我的構建我的視圖模型的代碼,我做的事:

viewModel.FooValues = new SelectList(FooCollection, "FooId", "FooText", viewModel.FooValue); 

然後在我的觀點:

@Html.DropDownListFor(m => m.FooValue, Model.FooValues) 

我希望這有助於。

+1

這只是創建相同的問題,只有'魔術字符串'現在已經移動到視圖模型,而不是視圖。 – 2011-04-02 17:57:15

+0

'魔法字符串'問題是這樣的:如果「FooId」變成「FooFooId」,那麼在編譯時它不會被視爲錯誤直到運行時。 – 2011-04-02 17:59:02

+0

另外,如果您的視圖模型具有類型SelectList的值,那麼第二次轉換就沒有意義。 – 2011-04-02 18:37:55

2

使用一個擴展方法和lambda表達式的功率,就可以做到這一點:

@Html.DropDownListFor(model => model.FooValue, Model.FooCollection.ToSelectList(x => x.FooText, x => x.FooId)) 

擴展方法如下:

public static class SelectListHelper 
{ 
    public static IList<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value) 
    { 
     var items = enumerable.Select(f => new SelectListItem() 
     { 
      Text = text(f), 
      Value = value(f) 
     }).ToList(); 
     items.Insert(0, new SelectListItem() 
     { 
      Text = "Choose value", 
      Value = string.Empty 
     }); 
     return items; 
    } 
} 
0

在C#6中可以採取的nameof優點並輕鬆擺脫這些魔術弦。

... = new SelectList(context.Set<User>(), nameof(User.UserId), nameof(User.UserName)); 
相關問題