How to set default value for DropDownList in View using ASP.NET MVC?

走远了吗. 提交于 2019-12-13 03:16:28

问题


I'm trying create a DropDownList in my View with data of a SelectList passed to my View using ViewBag:

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

In my View i create a WebGrid with a column representing this DropDownList like this:

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

However this list just uses the first item in the list as its default value. How to set another value of this list to its default value?

UPDATE:

When i try the following code:

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);
    }

I'm getting the following result:

However this is configured:

What I'm trying to achieve is this:

Key1 : DropDownlist with default value keyA

Key2 : Dropdownlist with default value keyB

Key3 : DropDownlist with default value keyC

Key4 : Dropdownlist with default value keyD


回答1:


I assume that you can achieve your desired result by manipulating the default SelectListItem in the list which is binded to SelectList.

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


来源:https://stackoverflow.com/questions/56935071/how-to-set-default-value-for-dropdownlist-in-view-using-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!