0

所以,这是我使用的 Html 助手:

        @Html.DropDownList("FK_gestCompte", User.Identity.Name)

这给出了这个 html 结果:

 <select id="FK_gestCompte" name="FK_gestCompte"><option value="">user3</option>
 <option value="1">user1</option>
 <option value="2">admin</option>
 <option value="3">user2</option>
 <option value="5">user3</option>
 </select>

我不明白如何设置第一行:

 <select id="FK_gestCompte" name="FK_gestCompte"><option value="5">user3</option>

我制作的选择列表已在控制器内创建,如下所示:

        ViewBag.FK_gestCompte = New SelectList(db.my_aspnet_users, "id", "Name")

任何想法?


这是Parv Sharma给出的解决方案:

控制器 :

        Dim ident As Integer = (From a In db.my_aspnet_users
                             Where a.name = User.Identity.Name
                             Select a.id).FirstOrDefault()
        ViewBag.FK_gestCompte = New SelectList(db.my_aspnet_users, "id", "Name", ident)

看法 :

        @Html.DropDownList("FK_gestCompte")
4

3 回答 3

2

going by the signature of the method you are using

  @Html.DropDownList("FK_gestCompte", User.Identity.Name)

im assuing that User.Identity.Name is an ienumerable of SelectListItem
so when you are filling this collection you can set any item as selected item using the Selected property of that item.

于 2012-05-04T07:53:39.977 回答
2
 its possible in this way

 @Html.DropDownListFor(model => model.UserType,
                       new SelectList(new List<Tuple<string, string>>
                       {
                         new Tuple<string, string>("1", "User"),                    
                          new Tuple<string, string>("2", "Admin"),                    
                        }, "Item1", "Item2", "2"))

  Admin will be selected by default as we have set "2" as a selected value
于 2012-05-04T07:51:03.320 回答
1

您可以尝试添加排序。

所以,db.my_aspnet_users.OrderByDescending(i => i.id)

编辑:刚刚看到第一个选项是<option value="">user3</option>

“user3”是否在您的数据源中出现两次?

编辑2:

尝试这个:

var users = db.my_aspnet_users.ToList();

var userSelectList = users.OrderBy(i => i.name)
                      .Select(thisUser =>
                          new SelectListItem
                          {
                              Selected = (thisUser.name == User.Identity.Name),
                              Text = thisUser.name,
                              Value = thisUser.id.ToString()
                          });

然后将助手替换为

@Html.DropDownList("userSelectList ") 
于 2012-05-04T07:47:37.450 回答