我做了不同的事情。这整件事非常令人沮丧。
在控制器中执行以下操作:
var percentagesFromDb = _service1.GetPercentagesFromDb(parameters);
var percentages = percentagesFromDb.ToDictionary(percentage => percentage.someKey,
percentage => percentage.someValue);
ViewData["selectedPercentages"] = percentages;
然后在模型中:
[Display(Name = "%")]
public string Percentage { get; set; }
private static Dictionary<string, string> GetPercentageList()
{
return new Dictionary<string, string>
{
{"100", "100%"},
{"90", "90%"},
{"80", "80%"},
{"70", "70%"},
{"60", "60%"},
{"50", "50%"},
{"40", "40%"},
{"30", "30%"},
{"20", "20%"},
{"10", "10%"}
};
}
public SelectList GetSelectList(string selected, object selectedPercentages)
{
var selectedDict = new Dictionary<string, string>();
if (selectedPercentages != null)
selectedDict = (Dictionary < string, string>) selectedPercentages;
var selectedvalue = selectedDict.ContainsKey(selected) ? selectedDict[selected] : "100";
Percentage = selectedvalue;
return new SelectList(GetPercentageList(), "Key", "Value");
}
最后在视图中:
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>@Html.LabelFor(m => m.Items, new {@class = "control-label"})</th>
<th>@Html.LabelFor(m => m.Percentage, new {@class = "control-label"})</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Items)
{
<tr>
<td>
@item.Value
</td>
<td>
@Html.DropDownListFor(m => m.Percentage,
Model.GetSelectList(item.Key, ViewData["selectedPercentages"]),
new {@class = "form-control", id = item.Key})
</td>
</tr>
}
</tbody>
</table>