Reputation: 1790
I have a registration page that requires State and Country selections. The items that populate these dropdowns come from an external database.
How do I make the call to populate those lists before the page renders?
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);
}
With the above setup I receive :
There is no ViewData item of type 'IEnumerable' that has the key 'State'.
Summary - I need to make a web service call to get data for 2 dropdowns before the page renders.
Upvotes: 2
Views: 1507
Reputation: 171
Try this
Model:
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" };
The 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))
Hope this will work.
Upvotes: 2