How to set different preconfigured default values for DropDownList in View using ASP.NET MVC?

ε祈祈猫儿з 提交于 2019-12-11 15:27:52

问题


I've created a program which has the ability to configure 2 keys to eachother, for example:

Key 1 = key a,
key 2 = key b,
key 3 = key c,
etc

With the following configuration page:

When pressing submit button it will send the configuration to the database:

This works fine, but now I am trying to create a edit page for the configuration. In this configuration page I'm using the query that gets the configuration from the database and puts this in a WebGrid:

Query:

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

This will get the entire configuration, on the left side of the WebGrid I just put the keys: key1, key2, key3, key4, etc. But on the right side I want the user to have a choice which key to connect to key1, key2, key3, etc. Therefore i use a dropdownlist, however this dropdownlist gets filled by a SelectListItem with the following code:

Controller:

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

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

WebGrid in View:

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

This will result in putting all the keys, keyA, KeyB, KeyC in a DropDownList but not as configured. I'm trying to get the default values in my dropdownlist as configured before.

Does anyone have suggestions how to achieve this?

Thanks in advance


回答1:


Your line

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

Does not work, as the second parameter to the Selectlist constructor is the default value.

As you are using a dictionary (the list variable) for the source you have to use the actual item in the dictionary as the SelectedValue.

This would work:

    ViewBag.OtherKeysList = new SelectList(list, list.Single(i => i.Key == "KeyB"));

Where "KeyB" in this case is the key that was selected and saved in the database.



来源:https://stackoverflow.com/questions/56947570/how-to-set-different-preconfigured-default-values-for-dropdownlist-in-view-using

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