使用不带魔术字符串的 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);
}
}
Is there an easy way to remove the use of Magic Strings when creating a SelectList, like in this example:
@Html.DropDownListFor( model => model.FooValue, new SelectList( Model.FooCollection, "FooId", "FooText", Model.FooValue) )
The magic strings being "FooId"
and "FooText"
The rest of the example is defined as follows:
//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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用扩展方法和 lambda 表达式的强大功能,您可以做到这一点:
扩展方法如下:
Using an extension method and the power of lambda expressions, you can do this:
The extension method is as follows:
我使用视图模型,因此我的 FooValues 下拉列表具有以下属性:
然后在构建视图模型的代码中我这样做:
然后在我看来:
我希望这会有所帮助。
I use View Models so I have the following properties for my FooValues dropdown:
and then in my code for building my view model I do:
Then in my view:
I hope this helps.
在 C# 6 中,您可以利用
nameof
并轻松摆脱这些神奇的字符串。In C# 6 you can take advantage of
nameof
and easily get rid of these magic strings.