【问题标题】:How to set default value for ASP.NET MVC DropDownList from ViewBag如何从 ViewBag 为 ASP.NET MVC DropDownList 设置默认值
【发布时间】:2019-12-15 09:13:56
【问题描述】:

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

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的项目

【问题讨论】:

  • 看看我的回答here看看有没有帮助
  • @Bosco 您的解决方案填充下拉列表并显示列表中的第一项。在我的场景中,默认值是动态的。

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


【解决方案1】:

如果model.Assignee带有值,如果是int,则默认为0,它将覆盖SelectListItem选择的值。

我建议设置model.Assignee

【讨论】:

  • 向我的模型添加一个新属性只是为了分配一个默认值似乎不是最好的方法。我的页面中有多个这样的下拉列表,我会尽可能地远离这个。还有其他解决方法吗?
【解决方案2】:
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 how to set default value

【讨论】:

  • 我需要在控制器而不是视图中确定默认值。
  • @amindomeniko 你想知道选择的值吗??
  • 是的,我在控制器中有一个默认文本“John Smith”
  • @amindomeniko 您将从选择的属性名称中收到它
【解决方案3】:

在您的视图集中:

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

【讨论】:

    【解决方案4】:

    当您已经定义了列表时。 使用这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      • 2016-07-12
      • 2010-09-23
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多