如何使用ASP.NET MVC为View中的DropDownList设置不同的预配置默认值? [英] How to set different preconfigured default values for DropDownList in View using ASP.NET MVC?

查看:79
本文介绍了如何使用ASP.NET MVC为View中的DropDownList设置不同的预配置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个程序,该程序能够互相配置2个键,例如:

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

具有以下配置页面:

按下提交按钮时,它将配置发送到数据库:

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

这可以正常工作,但是现在我正在尝试为配置创建一个编辑页面.在此配置页面中,我使用的查询是从数据库获取配置并将其放入WebGrid中的:

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:

查询:

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

这将获得整个配置,在WebGrid的左侧,我只放置了键:key1,key2,key3,key4等.但是在右侧,我希望用户可以选择要连接的键到key1,key2,key3等.因此,我使用了dropdownlist,但是此dropdownlist由SelectListItem填充,并带有以下代码:

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:

控制器:

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

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

视图中的WebGrid:

WebGrid in View:

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

这将导致将所有密钥keyA,KeyB,KeyC放入DropDownList中,但未按配置进行.我正在尝试从下拉列表中获取以前配置的默认值.

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?

预先感谢

推荐答案

您的行

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

不起作用,因为Selectlist构造函数的第二个参数是默认值.

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

当您使用字典( list 变量)作为源时,必须将字典中的实际项目用作 SelectedValue .

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.

这将起作用:

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

在这种情况下,"KeyB"是已选择并保存在数据库中的密钥.

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

这篇关于如何使用ASP.NET MVC为View中的DropDownList设置不同的预配置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆