在ASP.NET MVC 2中实现DropDownList的最佳方式? [英] Best way of implementing DropDownList in ASP.NET MVC 2?
问题描述
我试图理解使用 DropDownListFor
在ASP.NET MVC 2中实现 DropDownList
的最佳方式帮手。这是一个多部分的问题。
I am trying to understand the best way of implementing a DropDownList
in ASP.NET MVC 2 using the DropDownListFor
helper. This is a multi-part question.
首先,将列表数据传递给视图的最佳方式是什么?
First, what is the best way to pass the list data to the view?
- 通过包含数据
- 的
SelectList
属性传递您的模型中的列表通过ViewData
- Pass the list in your model with a
SelectList
property that contains the data - Pass the list in via
ViewData
中的列表如何在的DropDownList
?在我创建它时,我应该将其建立到 SelectList
还是有其他方法来告诉助手自动创建一个空值?
How do I get a blank value in the DropDownList
? Should I build it into the SelectList
when I am creating it or is there some other means to tell the helper to auto create an empty value?
最后,如果由于某些原因存在服务器端错误,并且我需要使用 DropDownList
重新显示屏幕,我需要获取列表值再次传入视图模型?这个数据在帖子之间没有维护(至少不是当我通过我的视图模型传递它),所以我要再次获取它(它被缓存)。我正在这样做吗?
Lastly, if for some reason there is a server side error and I need to redisplay the screen with the DropDownList
, do I need to fetch the list values again to pass into the view model? This data is not maintained between posts (at least not when I pass it via my view model) so I was going to just fetch it again (it's cached). Am I going about this correctly?
推荐答案
你最好的选择是在控制器中创建一个SelectList - 在这里使用我的扩展方法:
http:// blog。 wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc
Your best bet is to create a SelectList in your Controller - use my extension method here: http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc
使用与您相同的密钥将其导入ViewData属性名称:
ViewData [statusid] = MySelectList
Pop that into ViewData using the same key as your property name:
ViewData["statusid"]=MySelectList
然后只需使用 Html.DropDownFor(x => x.StatusID)
,你们都设置了。
Then just use Html.DropDownFor(x=>x.StatusID)
and you're all set.
这篇关于在ASP.NET MVC 2中实现DropDownList的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!