Using the DropDownList Helper with ASP.NET MVC

This post will teach you the basics of working with the DropDownList helper in an ASP.NET MVC Web application. The DropDownList helper used to create an HTML select list requires a IEnumerable , either explicitly or implicitly. That is, you can pass the IEnumerable explicitly to the DropDownList helper or you can add the IEnumerable to the ViewBag using the same name for the SelectListItem as the model property.
Let’s suppose you want to show the list of Animals as dropdownlist

public static List<String> GetPets()
        {
            List<string> petList = new List<string>();
            petList.Add("Dog");
            petList.Add("Cat");
            petList.Add("Hamster");
            petList.Add("Parrot");
            petList.Add("Gold fish");
            petList.Add("Mountain lion");
            petList.Add("Elephant");

            return petList;
        }

Open your controller method and add items to ViewBag item bypassing the item to SelectList.

public ActionResult Index()
        {

            ViewData["Pets"] = new SelectList(GetPets());
            return View();
        }

In your view add the following razor helper method. Run the application you will see that a dropdownlist is generated

@Html.DropDownList("pets")  

The above was very simple form.Let’s create a complex form with some other information. In this example, I am going to create a simple user registration form. Create two class named Country and Registration in the model folder and add the following code


public class Registration
  {
      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string County { get; set; }

  }
  public class Country
  {
      public int Id { get; set; }
      public string Name { get; set; }
  }

After that create a RegistrationViewModel class in a Model folder and paste the following code

public class RegistrationViewModel
    {
        private readonly List<Country> _countries;
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string County { get; set; }

        public int SelectedCountryID { get; set; }
        public RegistrationViewModel()
        {
            List<Country> countries = new List<Country>(){
                new Country{Id=1,Name="India"},
                new Country{Id=2,Name="USA"},
                new Country{Id=3,Name="UK"},
                new Country{Id=4,Name="Australia"},
                new Country{Id=5,Name="Nepal"},
            };
            _countries = countries;
        }
        public IEnumerable<SelectListItem> Contry
        {
            get { return new SelectList(_countries, "Id", "Name"); }
        }
    }

The tricky part here is that I have added a read-only property Country that returns a list of countries which I will pass to the DropDownListFor helper function. Create two action methods in your controller as below. Right-click on Create action method and generate a strong type view. Open the generated view and modify the Country section as below


    <div class="editor-field">
          @Html.DropDownListFor(model => model.SelectedCountryID, Model.Contry)
          @Html.ValidationMessageFor(model => model.County)

      </div>
public ActionResult Create()
        {
            RegistrationViewModel model = new RegistrationViewModel();
            return View(model);
        }
        [HttpPost]
        public ActionResult Create(RegistrationViewModel _model)
        {
            RegistrationViewModel model = _model;
            return View(model);
        }
@model eManagerDemo.Models.RegistrationViewModel

@{
  ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()
  @Html.ValidationSummary(true)

  <fieldset>
      <legend>RegistrationViewModel</legend>

      <div class="editor-label">
          @Html.LabelFor(model => model.FirstName)
      </div>
      <div class="editor-field">
          @Html.EditorFor(model => model.FirstName)
          @Html.ValidationMessageFor(model => model.FirstName)
      </div>

      <div class="editor-label">
          @Html.LabelFor(model => model.LastName)
      </div>
      <div class="editor-field">
          @Html.EditorFor(model => model.LastName)
          @Html.ValidationMessageFor(model => model.LastName)
      </div>

      <div class="editor-label">
          @Html.LabelFor(model => model.County)
      </div>
      <div class="editor-field">
          @Html.DropDownListFor(model => model.SelectedCountryID, Model.Contry)
          @Html.ValidationMessageFor(model => model.County)

      </div>

      <p>
          <input type="submit" value="Create" />
      </p>
  </fieldset>
}

<div>
  @Html.ActionLink("Back to List", "Index")
</div>

If you run the application by pressing F5 you will see the following output as shown below image.

Using the DropDownList Helper with ASP.NET MVC

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru