簡體   English   中英

如何從 ViewBag 設置 ASP.NET MVC DropDownList 的默認值

[英]How to set default value for ASP.NET MVC DropDownList from ViewBag

在控制器索引中,我有以下內容:

ViewBag.Assignees = (await GetAllUsers()).Select(a =>
            new SelectListItem
            {
                Text = a.DisplayName,
                Value = a.Username,
                Selected = a.DisplayName == "John Smith"
            }).OrderBy(x => x.Text).ToList();

在視圖中,我有以下內容:

 @Html.DropDownListFor(model => model.Assignee, 
                       ViewBag.Assignees as List<SelectListItem>, 
                       "Select Assignee", 
                       new { id = "ddlAssignee", @class = "form-control"})

下拉列表按預期填充,但是,確實存在的默認值 (selected = true) 未設置。 有人可以建議上面有什么問題嗎?

更新:

通過將SelectListItem.Value更改為a.DisplayName (與SelectedListItem.Text相同),我實現了它。 仍然不確定是什么阻止下拉列表顯示Selected = true的項目

如果model.Assignee帶有值,如果它是一個 int 則默認為 0,它將覆蓋SelectListItem選擇的值。

我建議設置model.Assignee

Here two ways that i use.
WAY 1

@Html.DropDownListFor(model => model.Assignee, 
                      ViewBag.Assignees as List<SelectListItem>, 
                      "Value", // property to be set as Value of dropdown item
                      "Text",  // property to be used as text of dropdown item
                      "1"), // value that should be set selected of dropdown
                      new { id = "ddlAssignee", @class = "form-control"})


WAY 2 

<select name="SelectName" value="1" class="w-100">
  @foreach (var item in ViewBag.Collection) {
    <option value="@item.Id">@item.Name</option>
  }
</select>

我希望它對你有用

@Html.DropDownListFor 如何設置默認值

在您的視圖集中:

 @Html.DropDownListFor(model => model.Assignee, 
                       ViewBag.Assignees as List<SelectListItem>, 
                       "Select Assignee", 
                       new { id = "ddlAssignee", @class = "form-control", @value = "Default value"})

當您已經定義了列表時。 用這個

@Html.DropDownList("CoverageDropDown", new SelectList(Model.youList, "Code", "Description",item.seletecItem), "Select")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM