问题描述
我在想,最好的做法是什么ASP.NET MVC填充常用dropdownlists时。举例来说,我有一个用于经常在我的应用程序一个国家和状态来选择。这似乎脏从我的控制器填充视图模型并绑定到视图模型,因为我想包含这样一个DropDownList每一个单一视图。
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.
人们如何填充其dropdownlists在这种情况下? - 与此自定义基类中出炉?辅助类等?
How do people populate their dropdownlists in such cases? - custom baseclass with this baked in? Helper classes, etc?
由于提前,
JP
推荐答案
您可以有一个 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 - 填充常用Dropdownlists的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!