Note that there are some explanatory texts on larger screens.

plurals
  1. POPopulating a DropDownList in MVC3?
    text
    copied!<p>I have a little problem in populating a drop down list in MVC3. I hope there would be somebody to give me a help on this.</p> <p>I am trying to render a View of Users which contains a DropDownList for Cities. This should be fetched from the Database. In fact, The User class has a ForeignKey of the City class.</p> <p>Here are the Controller and the View:</p> <pre><code>public ViewResult Index() { //return View(model); var DefaultCities = new[] { new {Name = "London"} }.ToList(); IEnumerable&lt;SelectListItem&gt; cities = unitOfWork.CityRepository.Get() as IEnumerable&lt;SelectListItem&gt;; ViewData["AllCities"] = cities != null ? new SelectList(cities.AsEnumerable(), "CityID", "Name") : new SelectList(DefaultCities.AsEnumerable(), "Name"); return View(unitOfWork.UserRepository.Get(orderBy: us =&gt; us.OrderByDescending(u =&gt; u.ID)).OfType&lt;User&gt;().ToList()); } </code></pre> <p>//The View</p> <pre><code>&lt;div class="editor-field"&gt; @Html.DropDownList(**"CityID"**, ViewData["AllCities"] as SelectList, "--Choose One--")) @Html.ValidationMessageFor(model =&gt; model.CityID) &lt;/div&gt; </code></pre> <p>But the following error displays:</p> <blockquote> <p>There is no ViewData item of type 'IEnumerable' that has the key 'CityID'.</p> </blockquote> <p>This is my first time on MVC! What does the 'CityID' refer to? What should I write as the first argument of <code>@Html.DropDownList</code>?</p> <p>As I have read on different articles, the argument mentioned should be the name of the form field. </p> <p>Can anyone suggest a sample code? Any help would be appreciated.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload