ASP.NET MVC - 填充常用的下拉列表 [英] ASP.NET MVC - Populate Commonly Used Dropdownlists
问题描述
我想知道在 ASP.NET MVC 中填充常用下拉列表时的最佳实践是什么.例如,我有一个经常在我的应用程序中使用的国家和州选择.对于我想要包含这样一个下拉列表的每个视图,填充视图模型并从我的控制器绑定到该视图模型似乎很脏.
I was wondering what the best practice is when populating commonly used dropdownlists in ASP.NET MVC. For instance, I have a Country and State select which is used often in my application. It seems dirty to populate viewmodel and bind to that viewmodel from my controller for every single view I want to contain such a dropdownlist.
在这种情况下,人们如何填充下拉列表?- 自定义基类与此烘焙?辅助类等?
How do people populate their dropdownlists in such cases? - custom baseclass with this baked in? Helper classes, etc?
提前致谢,
日本
推荐答案
您可以使用 RequiresStateList
属性将通用功能注入到需要它的操作中.
You can have a RequiresStateList
attribute to inject that common functionality to the actions that need it.
public class RequiresStateList : ActionFilterAttribute {
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.Controller.ViewData["StateList"] = GetStates();
}
}
还有你的动作
[RequiresStateList]
public ActionResult Index() {
return View();
}
现在您可以从视图中的 ViewData 中获取该列表.
Now you can get that list from the ViewData in your view.
这篇关于ASP.NET MVC - 填充常用的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!