我在选择 DropDownList 的值时遇到问题。我一直在阅读所有类似的帖子,但找不到解决方案。
实际的方法对我来说似乎非常好,因为我可以检查 SelectList 内的字段:
var selectList = new List<SelectListItem>(
from variable in someKindOfCollection
select new SelectListItem
{
Selected = variable.Property == selection,
Text = variable.Property,
Value = variable.Property
});
据说,这给了我完全的控制权。构建 selectList 后,我可以使用调试器检查变量。一切正常,其中之一已标记为“选定”属性。
然后我使用 DropDownListFor 以便在视图上显示:
@Html.DropDownListFor(
g => g.SomePropertyInModel , selectList, new { @class = "cssClass" })
但它不起作用,永远不会...“渲染”下拉列表,但没有选择任何内容。
多谢 :)
新例子
首先我想道歉。我一直在隐藏信息,当然完全是无意的。
所有代码都发生在 Razor For 循环内:
@foreach (var loopVariable in Model.Collection)
{
if (Model.SomeCondition != null)
{
selection = someValue;
}
var selectList = new List<SelectListItem>(
from variable in someKindOfCollection
select new SelectListItem
{
Selected = variable.Property == selection,
Text = variable.Property,
Value = variable.Property
});
@Html.DropDownListFor(
g => g.SomePropertyInModel , selectList, new { @class = "cssClass" })
}
那么, selectList 是一个局部变量导致了这种行为吗?抱歉,我没想到是这样的。