有一種簡單的方法來消除,使用魔法字符串創建時的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);
}
}
這只是創建相同的問題,只有'魔術字符串'現在已經移動到視圖模型,而不是視圖。 – 2011-04-02 17:57:15
'魔法字符串'問題是這樣的:如果「FooId」變成「FooFooId」,那麼在編譯時它不會被視爲錯誤直到運行時。 – 2011-04-02 17:59:02
另外,如果您的視圖模型具有類型SelectList的值,那麼第二次轉換就沒有意義。 – 2011-04-02 18:37:55