在ASP.NET MVC 2实施的DropDownList的最好方法? [英] Best way of implementing DropDownList in ASP.NET MVC 2?
问题描述
我想了解ASP.NET MVC 2实施的DropDownList
使用的最佳方法 DropDownListFor
帮手。这是一个多部分的问题。
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 code>
- 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 /我最喜欢-助手换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:计算机[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屋!