ASP.NET MVC - Html.DropDownList - 值通过ViewData.Model不设置 [英] ASP.NET MVC - Html.DropDownList - Value not set via ViewData.Model
问题描述
刚刚开始使用ASP.NET MVC玩,并绊倒了以下情况。这感觉很像一个错误,但如果它不是,解释将AP preciated:)
Have just started playing with ASP.NET MVC and have stumbled over the following situation. It feels a lot like a bug but if its not, an explanation would be appreciated :)
该视图包含pretty基本的东西
The View contains pretty basic stuff
<%=Html.DropDownList("MyList", ViewData["MyListItems"] as SelectList)%>
<%=Html.TextBox("MyTextBox")%>
当不使用一个模型,价值和选择的项目被设定为预期:
When not using a model, the value and selected item are set as expected:
//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();
}
但是,试图通过模型加载时,文本框具有预期设定的值,但是下拉犯规获得一个选择的项目设置。
But when trying to load via a model, the textbox has the value set as expected, but the dropdown doesnt get a selected item set.
//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);
}
任何想法?我就可以了目前的想法是,使用模型时,或许,我们仅限于上设置选择列表的构造所选择的项目,而不是使用可视数据(其中正常工作),并与模型通过选择列表中 - 这将有益处清洁code了一点 - 我只是想知道为什么这种方法doesnt工作....
Any ideas? My current thoughts on it are that perhaps when using a model, we're restricted to setting the selected item on the SelectList constructor instead of using the viewdata (which works fine) and passing the selectlist in with the model - which would have the benefit of cleaning the code up a little - I'm just wondering why this method doesnt work....
非常感谢您的任何建议。
Many thanks for any suggestions
推荐答案
一束卷边和hawing后它归结为以下行code的
After a bunch of hemming and hawing it boils down to the following line of code
if (ViewData.ModelState.TryGetValue(key, out modelState))
这意味着MVC正试图通过只看ViewData字典&LT来解决的价值;>对象,而不是向下遍历到ViewData.Model对象
which means MVC is trying to resolve the value by only looking at the ViewData Dictionary<> object and not traversing down into the ViewData.Model object.
这是否是一个错误,限制或设计决定我不知道。但是,您可以修复它通过以下方式:
Whether that's a bug, limitation or design decision I'm not sure. However, you can fix it the following way:
<%= Html.TextBox("MyTextBox", ViewData.Model.MyTextBox) %>
这篇关于ASP.NET MVC - Html.DropDownList - 值通过ViewData.Model不设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!