设置下拉列表中选定的值
大家好,我在其中一页上的下拉列表中遇到了奇怪的错误!
我对 3 个下拉列表使用了这样的代码:
//GetTypes returns collection of all availibale types from database
ViewData["Types"] = new SelectList(dataManager.IssueTypes.GetTypes(), "Id", "Title", issue.Type);
效果很好!
但是当我这样使用它时:
// GetRoles returns collection of all availibale roles
ViewData["Roles"] = new SelectList(dataManager.Membership.GetRoles(), "RoleId", "RoleName",
dataManager.Membership.GetUserRole(id));
它总是显示默认值! 我用调试器多次查看这段代码,但一切似乎都很好! 将不胜感激任何形式的帮助!
查看代码:
%: Html.DropDownList("RoleId", ViewData["Roles"] as IEnumerable<SelectListItem>)%>
Hello every one i have strange bug with dropdownlist on one of the pages!
I used code such as this for 3 dropdownlists:
//GetTypes returns collection of all availibale types from database
ViewData["Types"] = new SelectList(dataManager.IssueTypes.GetTypes(), "Id", "Title", issue.Type);
and it works great!
But when i used it like this:
// GetRoles returns collection of all availibale roles
ViewData["Roles"] = new SelectList(dataManager.Membership.GetRoles(), "RoleId", "RoleName",
dataManager.Membership.GetUserRole(id));
it always shows default value!
I looked trough this code with debuger many times but everithing seems fine!
Will be grateful for any kind of help!
View code:
%: Html.DropDownList("RoleId", ViewData["Roles"] as IEnumerable<SelectListItem>)%>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用视图模型而不是 ViewData 怎么样?每当我看到有人使用 ViewData 时,我都觉得自己有义务指出这一点,我个人认为这是最佳实践。
因此,首先定义视图将使用的视图模型:
现在让我们继续讨论将填充此视图模型并将其传递给视图的控制器操作:
好的,现在您应该确保
SelectedRoleId
表示Roles
集合中存在的字符串值。这将预选下拉列表。最后是强类型视图:
How about using view models instead of
ViewData
? Everytime I see someone usingViewData
I feel myself in the obligation to point this out as personally I consider as best practices.So start with defining a view model that will be used by your view:
Now let's move on to the controller action that will populate this view model and pass it to the view:
OK, now you should ensure that
SelectedRoleId
represents a string value which is present in theRoles
collection. This is what will preselect the dropdown list.And finally the strongly typed view:
我不知道你的 dataManager.Membershop.GetUserRole(id) 返回什么类型?
但是您需要更改此调用中的第四个参数:
更改为:
注意最后的 RoleId 吗?您指定为所选项目的对象应该是该项目的 Value 属性的值 - 而不是整个对象。
I don't know what type your dataManager.Membershop.GetUserRole(id) returns?
But you need to change the 4th parameter in this call:
To something like:
Notice the RoleId at the end? The object you specify as the selected item, should be the value of the item's Value property - not the entire object.