选择一个值到 DropDownList 中
我有以下声明:
<%: Html.DropDownList("dropCity", new[] { new SelectlistItem { Text = "City1", Value = 1}, new SelectlistItem { Text = "City2", Value = 2}, new SelectlistItem { Text = "City3", Value = 3}})%>
假设我的控制器发送到包含此下拉列表的 aspx 页面,其值为“3”,我如何设置此下拉列表以在页面加载时选择此选项?
感谢您的帮助!
I have the following statement:
<%: Html.DropDownList("dropCity", new[] { new SelectlistItem { Text = "City1", Value = 1}, new SelectlistItem { Text = "City2", Value = 2}, new SelectlistItem { Text = "City3", Value = 3}})%>
Suppous that my controller sent to the aspx page that contais this dropdownlist a variable with the value "3", how can I set this dropdownlist to select this option when the page loads ?
Thanks for the help !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用视图模型:
然后让您的控制器填充此视图模型:
最后在强类型视图中:
Use view models:
then have your controller populate this view model:
and finally in your strongly typed view:
如果您的控制器传递“3”,为什么不让它传递 SelectListItem 的所有列表呢?
然后,您将在或控制器中执行类似的操作:
并在视图中以这种方式接收它:
这样,选择正确城市背后的所有逻辑都在控制器中,就像从一开始就应该的那样。
If your controller is passing '3' why not making it pass the all list of SelectListItem instead?
Then you would do something like this in or controller:
And received it this way within the view:
This way the all logic behind selecting the proper city is in the controller, as it should since the beginning.
创建 selectlistitem 时,只需执行以下操作:
When you create the selectlistitem, just do: