【问题标题】:Razor default selection in dropdownlist?下拉列表中的剃刀默认选择?
【发布时间】:2016-09-20 20:15:23
【问题描述】:

我在 Razor 中有以下声明:

@Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>, ViewBag.CurrentUserRole as string, new { @class = "form-control" }),它会在页面加载时生成如下所示的下拉列表:

当我点击下拉箭头时,我看到:

所以基本上,用户角色是重复的。我怎样才能改变它,而不是制作一个新的重复元素,它默认为它应该是的元素?基本上,由于ViewBag.RolesEdit 是一个列表,并且ViewBag.CurrentUserRole 保证有一个元素正好等于上述列表中的一项,我如何循环遍历列表以相互比较并设置默认值?

谢谢。

【问题讨论】:

  • 你可能想看看这个answer。
  • 是CurrentUserRole设置为textRegularUser还是设置为value对应RegularUser?
  • @stephen.vakil 它在控制器中设置为text,如下所示:ViewBag.CurrentUserRole = user.UserRole(); 其中user 是身份框架中的一种用户。
  • @Win 在重构代码时我会牢记这一点。

标签: c# html asp.net asp.net-mvc razor


【解决方案1】:

当使用Html.DropDownList辅助方法时,要设置一个选项被预选,您只需将该选项的值设置到ViewBag字典中,使用相同的键来生成选择元素。

@Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>)

假设您的操作方法是将ViewBag.SelectedRole 设置为您要选择的选项的value。

ViewBag.RolesEdit= new List<SelectListItem>{     
   new SelectListItem { Value="Administrator", Text="Administrator"},
   new SelectListItem { Value="Employees", Text="Employees"},
   new SelectListItem { Value="RegularUser", Text="Regular User"},
}
ViewBag.SelectedRole  ="RegularUser";
return View();

如果您更喜欢在强类型视图和视图模型中使用 Html.DropDownListFor 辅助方法,您可以关注这篇文章

What is the best ways to bind @Html.DropDownListFor in ASP.NET MVC5?

【讨论】:

  • 谢谢,这行得通。我使用了ViewBag.SelectedRole = user.UserRole();,而不是像您的答案那样对其进行硬编码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
相关资源
最近更新 更多