如何编写一个简单的Html.DropDownListFor()?
在 ASP.NET MVC 2 中,我想编写一个非常简单的下拉列表,它提供静态选项。例如,我想提供“红色”、“蓝色”和“绿色”之间的选择。
In ASP.NET MVC 2, I'd like to write a very simple dropdown list which gives static options. For example I'd like to provide choices between "Red", "Blue", and "Green".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
请参阅这篇 MSDN 文章和Stack Overflow 上的示例用法。
假设您有以下 Linq/POCO 类:
假设您有以下模型:
最后,假设您有以下颜色列表。它们可能来自 Linq 查询、静态列表等:
在您看来,您可以创建一个下拉列表,如下所示:
See this MSDN article and an example usage here on Stack Overflow.
Let's say that you have the following Linq/POCO class:
And let's say that you have the following model:
And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:
In your view, you can create a drop down list like so:
或者您可以不编写任何类,直接将类似的内容放入视图中。
or you can write no classes, put something like this directly to the view.
避免大量繁琐的指法
通过从模型中的字典开始,在视图中将其转换为列表进行显示,
Avoid of lot of fat fingering by starting with a Dictionary in the Model
In the View convert it to a list for display
您好,这是我在一个项目中的做法:
我希望它对某人有所帮助。谢谢
Hi here is how i did it in one Project :
I hope it helps Somebody. Thanks
或者,如果它来自数据库上下文,您可以使用
Or if it's from a database context you can use
与“请选择一项”
源自代码:Master Programmer && 乔尔·瓦伦德;
King参考:https://stackoverflow.com/a/1528193/1395101JaredPar;
感谢编程大师 && 乔尔·瓦伦德 && 贾里德帕;
祝朋友好运。
With "Please select one Item"
Derived from the codes: Master Programmer && Joel Wahlund ;
King Reference : https://stackoverflow.com/a/1528193/1395101 JaredPar ;
Thanks Master Programmer && Joel Wahlund && JaredPar ;
Good luck friends.
我认为这个答案与 Berat 的类似,因为您将 DropDownList 的所有代码直接放在视图中。但我认为这是创建 ay/n (布尔)下拉列表的有效方法,所以我想分享它。
给初学者的一些注意事项:
第一次,并且不链接到任何其他地方
MVC 应用程序,因此您可以将其命名为您想要的名称 - 'x'、'model'、'm' 等。
希望这对某人有帮助,
I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.
Some notes for beginners:
first time, and doesn't link to anything else anywhere else in the
MVC app, so you can call it what you want - 'x', 'model', 'm' etc.
Hope this helps someone,