2011-03-30 86 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));