DropDownListFor不选择价值 [英] DropDownListFor Not Selecting Value
问题描述
我使用的是编辑页面内的DropDownListFor辅助方法,而我没有任何运气得到它的选择,我指定的值。我注意到一个<一个href=\"http://stackoverflow.com/questions/1916462/dropdownlistfor-in-editortemplate-not-selecting-value\">similar问题的#2。建议的解决方法是,填充在视图code你的SelectList。问题是,我已经尝试这样做,它仍然没有工作。
I'm using the DropDownListFor helper method inside of an edit page and I'm not having any luck getting it to select the value that I specify. I noticed a similar question on Stackoverflow. The suggested workaround was to, "populate your SelectList in the view code". The problem is that I've already tried this and it's still not working.
<%= Html.DropDownListFor(model => model.States, new SelectList(Model.States.OrderBy(s => s.StateAbbr), "StateAbbr", "StateName", Model.AddressStateAbbr), "-- Select State --")%>
我设置一个断点,并已验证model.AddressStateAbbr的存在(和有效性)。我只是不知道我错过了什么。
I have set a breakpoint and have verified the existence (and validity) of model.AddressStateAbbr. I'm just not sure what I'm missing.
推荐答案
研究了一个小时后,我发现选择不会被设置为 DropDownListFor
。原因是你正在使用ViewBag的名字一样的模型的属性。
After researching for an hour, I found the problem that is causing the selected to not get set to DropDownListFor
. The reason is you are using ViewBag's name the same as the model's property.
示例
public class employee_insignia
{
public int id{get;set;}
public string name{get;set;}
public int insignia{get;set;}//This property will store insignia id
}
// If your ViewBag's name same as your property name
ViewBag.Insignia = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);
查看
@Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.Insignia, "Please select value")
选择的选项将不设置为DropDownList,但是当你改变ViewBag的名字,以不同的名称选择的选项将显示正确的。
The selected option will not set to dropdownlist, BUT When you change ViewBag's name to different name the selected option will show correct.
示例
ViewBag.InsigniaList = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);
查看
@Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.InsigniaList , "Please select value")
这篇关于DropDownListFor不选择价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!