我有一个注册页面,需要选择州和国家/地区。填充这些下拉列表的项目来自外部数据库。
如何在页面呈现之前调用来填充这些列表?
public class RegisterModel
{
...
public IEnumerable<SelectListItem> States {get;set;}
public IEnumerable<SelectListItem> Countries {get;set;}
...
}
//Register.cshtml
@model Adw.Web.Models.RegisterModel
@Html.LabelFor(m => m.State)
@Html.DropDownListFor(m =>m.State, new SelectList(Model.States))
//Controller
public ActionResult Register()
{
.....
RegisterModel rm = new RegisterModel();
//The factories return List<string>
rm.States = new SelectList(stateFactory.Create(states.Payload));
rm.Countries = new SelectList(countryFactory.Create(country.Payload));
return View(rm);
}
通过上述设置,我收到:
不存在具有键“State”的“IEnumerable”类型的 ViewData 项。
摘要 - 我需要在页面呈现之前进行 Web 服务调用以获取 2 个下拉列表的数据。
最佳答案
试试这个
型号:
public class RegisterModel
{
...
public IList<string> States { get; set; }
public IList<string> Countries { get; set; }
....
}
Controller :
RegisterModel rm = new RegisterModel();
// read data from the database and add to the list
rm.States = new List<string> { "NY", "LA" };
rm.Countries = new List<string> { "USA", "Canada" };
View :
@Html.LabelFor(x=>x.Countries)
@Html.DropDownListFor( x=>x.Countries, new SelectList(Model.Countries))
@Html.LabelFor(x=>x.States)
@Html.DropDownListFor( x=>x.States, new SelectList(Model.States))
希望这会起作用。
关于asp.net-mvc - 如何加载 DropdownList 的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990257/