刚刚开始使用 ASP.NET MVC 并偶然发现了以下情况。感觉很像一个错误,但如果不是,我们将不胜感激:)
视图包含非常基本的东西
<%=Html.DropDownList("MyList", ViewData["MyListItems"] as SelectList)%>
<%=Html.TextBox("MyTextBox")%>
不使用模型时,按预期设置值和选定项:
//works fine
public ActionResult MyAction(){
ViewData["MyListItems"] = new SelectList(items, "Value", "Text"); //items is an ienumerable of {Value="XXX", Text="YYY"}
ViewData["MyList"] = "XXX"; //set the selected item to be the one with value 'XXX'
ViewData["MyTextBox"] = "ABC"; //sets textbox value to 'ABC'
return View();
}
但是当尝试通过模型加载时,文本框的值按预期设置,但下拉菜单没有获得选定的项目集。
//doesnt work
public ActionResult MyAction(){
ViewData["MyListItems"] = new SelectList(items, "Value", "Text"); //items is an ienumerable of {Value="XXX", Text="YYY"}
var model = new {
MyList = "XXX", //set the selected item to be the one with value 'XXX'
MyTextBox = "ABC" //sets textbox value to 'ABC'
}
return View(model);
}
有任何想法吗?我目前对此的想法是,也许在使用模型时,我们仅限于在 SelectList 构造函数上设置所选项目,而不是使用视图数据(工作正常)并将选择列表与模型一起传递——这将有好处稍微清理一下代码 - 我只是想知道为什么这种方法不起作用....
非常感谢您的任何建议