首页 > 解决方案 > 如何使用 ASP.NET MVC 在 View 中设置 DropDownList 的默认值?

问题描述

我正在尝试在我的视图中创建一个 DropDownList,其中使用 ViewBag 将 SelectList 的数据传递给我的视图:

ViewBag.OtherKeysList = new SelectList(list, "OtherKey");

在我的视图中,我创建了一个 WebGrid,其中有一列表示此 DropDownList,如下所示:

 grid.Column(columnName: "OtherKey", header: "OtherKey", format: @<text>@Html.DropDownList("OtherKey", (IEnumerable<SelectListItem>)ViewBag.OtherKeysList, new { @class = "extra-class" })</text>)))

但是,此列表仅使用列表中的第一项作为其默认值。如何将此列表的另一个值设置为其默认值?

更新:

当我尝试以下代码时:

public ActionResult EditMapping(int id)
    {
        var list = new ListWithDuplicates();

        var v = (from a in dbProducts.MapperConfigs
                 where
                    a.MappingID.Equals(id)
                 select a
                   );

        foreach (var item in v)
        {
            list.Add(item.OtherKey, item.OtherKeyType);
        }

        ViewBag.TotalRows = v.Count();

        ViewBag.OtherKeysList = list.Select(x => new SelectListItem() { Text = x.Key, Value = x.Key, Selected = x.Key == "keyC" ? true : false });

        ViewBag.MappingName = (from a in dbProducts.MappingNames
                               where
                                  a.MappingID.Equals(id)
                               select a.Name
                   ).First();

        var data = v.ToList();
        return View(data);
    }

我得到以下结果:

在此处输入图像描述

但是这是配置的:

在此处输入图像描述

我想要实现的是:

Key1 :具有默认值 keyA 的下拉列表

Key2:具有默认值 keyB 的下拉列表

Key3 :具有默认值 keyC 的下拉列表

Key4 :具有默认值 keyD 的下拉列表

标签: asp.netselectrazormodel-view-controllerdropdown

解决方案


我假设您可以通过操作绑定到 SelectList 的默认 SelectListItem 来实现您想要结果list

var defaultItem = new SelectListItem()
{
   Value = 1,
   Text = "Default Item",
   Selected = true
};

推荐阅读