Jac*_*cob 6 asp.net-mvc asp.net-mvc-3
我在选择DropDownList的值时遇到问题.我一直在阅读所有类似的帖子,我无法得到解决方案.
实际的方法对我来说似乎非常好,因为我可以检查SelectList中的字段:
var selectList = new List<SelectListItem>(
from variable in someKindOfCollection
select new SelectListItem
{
Selected = variable.Property == selection,
Text = variable.Property,
Value = variable.Property
});
Run Code Online (Sandbox Code Playgroud)
据说,这给了我完全的控制权.在构建了selectList之后,我可以使用调试器检查变量.一切都很好,其中一个标有"Selected"属性.
然后我使用DropDownListFor来显示视图:
@Html.DropDownListFor(
g => g.SomePropertyInModel , selectList, new { @class = "cssClass" })
Run Code Online (Sandbox Code Playgroud)
但它没有用,从来没有..."渲染"下拉列表,但没有选择任何东西.
非常感谢 :)
新示例首先,我要道歉.我一直在隐藏信息,当然是完全无意的.所有代码都发生在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" })
}
Run Code Online (Sandbox Code Playgroud)
那么,selectList是导致行为的局部变量的事实?对不起,我没想到就是这样.
我建议使用视图模型:
\n\npublic ActionResult Index()\n{\n var model = new MyViewModel\n {\n // this will preselect the item with value = "2.400 \xe2\x82\xac" in the collection\n SelectedValue = "2.400 \xe2\x82\xac",\n\n Values = someKindOfCollection\n };\n return View(model);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n并在视图中:
\n\n@Html.DropDownListFor(\n g => g.SelectedValue, \n new SelectList(Model.Values, "SomePropertyForValue", "SomePropertyForText"), \n new { @class = "cssClass" }\n)\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
21281 次 |
最近记录: |