简体   繁体   English

如何使用ASP.NET MVC为View中的DropDownList设置不同的预配置默认值?

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

I've created a program which has the ability to configure 2 keys to eachother, for example: 我创建了一个程序,该程序能够互相配置2个键,例如:

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: 在此配置页面中,我使用的查询是从数据库获取配置并将其放入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: 这将获得完整的配置,在WebGrid的左侧,我只放置了键:key1,key2,key3,key4等。但是在右侧,我希望用户可以选择将哪个键连接到key1, key2,key3等。因此,我使用了一个dropdownlist,但是此dropdownlist由一个SelectListItem填充,并带有以下代码:

Controller: 控制器:

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

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

WebGrid in View: 视图中的WebGrid:

 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. 这将导致将所有密钥keyA,KeyB和KeyC放入DropDownList中,但未按配置进行。 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 提前致谢

Your line 你的线

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

Does not work, as the second parameter to the Selectlist constructor is the default value. 不起作用,因为Selectlist构造函数的第二个参数是默认值。

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 . 在为源使用字典( 列表变量)时,必须将字典中的实际项目用作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. 在这种情况下,“ KeyB”是已选择并保存在数据库中的密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM