如何加载DropdownList的列表

时间:2013-02-20 21:27:16

标签: asp.net-mvc asp.net-mvc-4

我有一个需要州和国家/地区选择的注册页面。填充这些下拉列表的项目来自外部数据库。

如何在页面呈现之前调用填充这些列表?

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);
    }

通过以上设置我收到:

没有类型为'IEnumerable'的ViewData项具有键'State'。

摘要 - 我需要进行Web服务调用,以便在页面呈现之前获取2个下拉列表的数据。

1 个答案:

答案 0 :(得分:2)

试试这个

型号:

public class RegisterModel
{
    ...
    public IList<string> States { get; set; }
    public IList<string> Countries { get; set; }
    ....
}

控制器:

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" };

观点:

@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))

希望这会奏效。

相关问题