2013-02-20 59 views
2

我有一个需要州和国家选择的注册页面。填充这些下拉列表的项目来自外部数据库。如何为DropdownList加载列表

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

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的项目。

总结 - 我需要做一个web服务调用,以在页面呈现之前获取2个下拉列表的数据。

+0

我最近回答了这样的问题,也许那里的信息会帮助你。 http://stackoverflow.com/questions/14714923/set-a-default-value-for-a-dropdownlist-from-a-list-coming-from-another-controlle/14715206#14715206 – mmeasor 2013-02-20 21:56:57

+0

我试图设置它正如您的链接中所建议的那样,但仍似乎无法使其发挥作用。我已更新我的帖子以反映这些更改。 – Zholen 2013-02-21 05:27:20

回答

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

希望这会工作。

+0

好极了!非常感谢,我不知道为什么这对我来说似乎很难。尽管如此,我的用户准备好提交表单后,如何检索选定的值?我还有另外两个名为State和Country的字符串属性,我试图填充,但也许我不需要? – Zholen 2013-02-21 16:12:42

+1

致@Zholen。您可以在methods参数中使用“FormCollection集合”。请参阅以下链接[链接](http://stackoverflow.com/questions/15007068/mvc-4-how-to-get-the-selected-item-from-a-dropdown-list)。 – Murtoza 2013-02-21 16:38:24