Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# dropdownlist中的Razor默认选择?_C#_Html_Asp.net_Asp.net Mvc_Razor - Fatal编程技术网

C# dropdownlist中的Razor默认选择?

C# dropdownlist中的Razor默认选择?,c#,html,asp.net,asp.net-mvc,razor,C#,Html,Asp.net,Asp.net Mvc,Razor,我有以下声明: @Html.DropDownList(“SelectedRole”,ViewBag.RolesEdit作为列表,ViewBag.CurrentUserRole作为字符串,new{@class=“form control”}),它会在页面加载时生成一个如下所示的下拉列表: 当我点击下拉箭头时,我看到: 因此,用户角色基本上是重复的。我如何更改它,使它默认为它应该是的元素,而不是创建一个新的重复元素?基本上,由于ViewBag.RolesEdit是一个列表,并且ViewBag.C

我有以下声明:

@Html.DropDownList(“SelectedRole”,ViewBag.RolesEdit作为列表,ViewBag.CurrentUserRole作为字符串,new{@class=“form control”})
,它会在页面加载时生成一个如下所示的下拉列表:

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

因此,用户角色基本上是重复的。我如何更改它,使它默认为它应该是的元素,而不是创建一个新的重复元素?基本上,由于
ViewBag.RolesEdit
是一个列表,并且
ViewBag.CurrentUserRole
保证有一个元素正好等于指定列表中的一个项目,我如何循环列表以相互比较并设置默认值


谢谢。

使用
Html.DropDownList
helper方法时,要设置一个要预选的选项,只需将该选项的值设置到ViewBag字典中,该值与生成SELECT元素所用的键相同

@Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>)
如果您更喜欢使用带有强类型视图和视图模型的
Html.DropDownListFor
helper方法,您可以阅读以下文章


您可能想看看这个。是否将
CurrentUserRole
设置为
text
RegularUser
或设置为与
RegularUser
相对应的
?@stephen.vakil它在控制器中设置为
text
,如下所示:
ViewBag.CurrentUserRole=user.UserRole()
where
user
是身份框架中的一种用户。@Win在重构代码时,我会记住这一点。谢谢,这很有效。我使用了
ViewBag.SelectedRole=user.UserRole()而不是像你们的答案那个样硬编码。
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();