Using the DropDownList Helper with ASP.NET MVC


This post will teach you the basics of working with the DropDownList helper 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 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 by passing the item to SelectList.

public ActionResult Index()
        {

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

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

@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 model folder and add 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 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 readonly property Country that returns list of countries which I will pass to DropDownListFor helper function.Create two action methods in your controller as below.Right click on Create action method and generate strongly type view.Open the genrated 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 following output as shown in below image.


No comments:

Post a Comment