创建SelectList时是否有一种简单的方法可以删除Magic Strings的使用,如下例所示:
@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 :(得分:3)
使用扩展方法和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;
}
}
答案 1 :(得分:0)
我使用View Models,因此我的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)
我希望这会有所帮助。
答案 2 :(得分:0)
在C#6中,您可以利用nameof
轻松摆脱这些神奇的弦乐。
... = new SelectList(context.Set<User>(), nameof(User.UserId), nameof(User.UserName));