如何从 DropDownListFor 列表中选择一个项目? (MVC3)
我使用此代码填充下拉列表(并且工作正常):
@Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text"), "Please Select a Country")
有时,此视图还会获取预先选择的国家/地区的数据,因此我想选择该国家/地区。
我尝试过:
@Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text", "United States"), "Please Select a Country")
但这没有用。我也尝试过该物品的价值,但没有成功。
我做错了什么?
另外,有没有办法在创建后访问/修改该元素? (使用 C# 而不是 javascript)
谢谢!
I'm populating a drop down list using this code (and it works fine):
@Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text"), "Please Select a Country")
Sometimes, this view also gets data of a pre-selected country, so I want to select that country.
I tried:
@Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text", "United States"), "Please Select a Country")
But this didn't work. I also tried the value of the item, and no luck.
What am I doing wrong?
Also, is there a way to access / modify that element after creation? (using C# not javascript)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Model.Countries
列表中有 2 个属性:Text
和Value
。因此,如果您想在下拉列表中预选给定项目,则应使用 value:,该值假定在 Model.Countries 中您有一个带有
Value="us"
的项目。作为一种替代方案,您可以在返回视图的控制器操作中执行此操作:
并且在视图中您可以简单地:
这将预选择带有
Value="us"
的元素(我的示例中的第三个)。There are 2 properties in the
Model.Countries
list: theText
and theValue
. So if you want to preselect a given item in the dropdown you should use the value:which assumes that in Model.Countries you have an item with
Value="us"
.As an alternative you could do this inside the controller action that is returning the view:
and in the view you could simply:
which will preselect the element with
Value="us"
(the third one in my example).