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
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.