了解下拉列表,我试图添加一个RSVP创建页面为nerddinner在
Scott Gu’s blog与Html.DropDownList列出可用的晚餐.
我可以得到下拉列表填充,但是我无法得到下拉菜单来预先选择我想要的值(“Sample Dinner 2”).我使用一个启动器在db中种几个晚餐对象.数据库是使用EF’代码第一方法’sql ce 4.对不起,我知道这是一个v常见的问题,恨问,但老实说,花了相当多的时间,但不能让它工作:
视图模型
public class RSVPviewmodel { public SelectList DinnersList { get; set; } public RSVP Rsvp { get; set; } public string SelectedItem { get; set; } }
调节器
// //GET: /RSVP/Create public ActionResult Create() { RSVP rsvp = new RSVP(); string selected = "Sample Dinner 2"; var typeList = new SelectList(dbc.Dinners.ToList(),"DinnerID","Title",selected); var viewmodel = new RSVPviewmodel { DinnersList = typeList,Rsvp = rsvp,SelectedItem = selected }; return View("Create",viewmodel); }
视图
@Html.DropDownListFor(model => model.Rsvp.DinnerID,Model.DinnersList)
HTML结果
<select data-val="true" data-val-number="The field DinnerID must be a number." data-val-required="The DinnerID field is required." id="Rsvp_DinnerID" name="Rsvp.DinnerID"> <option value="1">Sample Dinner 1</option> <option value="2">Sample Dinner 2</option> </select>
因此,当页面加载时,不会预先选择值为“Sample Dinner 2”的下拉列表.列表显示确定,并在进行选择时设置正确的DinnerID,然后单击提交.
也试试:
@Html.DropDownListFor(x => x.SelectedItem,Model.DinnersList)
但没有设置或绑定到Rsvp.DinnerID.
这从列表中预先选择但不绑定(或设置Rsvp.DinnerID)
@Html.DropDownList("DinnersList")
我想保持它mvc3所以要使用强力类型实现使用viewmodel方法(没有ViewData),最好使用Html.DropDownListFor(不是Html.DropDownList).对于这种情况来说,这个viewView似乎是不必要的.
谢谢!
EDIT1
思考我应该使用selectList的selectListItems我尝试这个详细的方法:
RSVP rsvp = new RSVP(); string selected = "2"; List<SelectListItem> dinners = new List<SelectListItem>(); foreach (Dinner dinner in dbc.Dinners.ToList()) { SelectListItem slDinner = new SelectListItem(); slDinner.Value = dinner.DinnerID.ToString(); slDinner.Text = dinner.Title; slDinner.Selected = (slDinner.Value == selected); dinners.Add(slDinner); } var dinnersList = new SelectList(dinners,"Value","Text",selected); var viewmodel = new RSVPviewmodel { DinnersList = dinnersList,SelectedItem = selected };
但仍然没有工作.我应该使用viewmodel SelectedItem属性:@ Html.DropDownListFor ..不知何故?就像是 :
@Html.DropDownListFor(x => x.SelectedItem,Model.DinnersList)
但是如何获取一个选定的值来设置Rsvp.DinnerID.我认为这叫做绑定.
解决方法
阅读
here和
here后,我终于明白HtmlDropDownlistFor如何根据您的模型自动在下拉列表中选择正确的项目 – 在RSVP中选择一个dinnerID(dinner.dinnerID的外键)将导致包含Dinner.DinnerID列表的下拉列表预先选择那个价值.对于SelectList或viewmodel中的selectedValue,我无需考虑.
解:
// //GET: /RSVP/Create public ActionResult Create() { //automatically preselects matching DinnerID in the Dinner dropdownlist var rsvp = new RSVP {DinnerID = 2 }; var typeList = new SelectList(dbc.Dinners.ToList(),"Title"); var viewmodel = new RSVPviewmodel { DinnersList = typeList,Rsvp = rsvp}; return View("Create",viewmodel); }