Sunday, 14 October 2012

Adding Dropdown list in ASP.NET MVC 3.0




Introduction
We have genre table and movie table. Let’s say that we want to add genre to movie, for instance genre is “Action” and our Movie is “Die Hard”.


In controller we want to get all genres and pass them to view, so the user can select genre for movie.



public ActionResult Movie(int movieID)
        {
            try
            {
              

                var genreList = from genre in dbContext.genres
    select genre;

               

                var list = genre.ToList();

                ViewData["genreList"] = list;

                return View(model);
            }
            catch
            {
                string Error = "Something went wrong, please try again. If error    occurs again please contact Administrator";
                ViewData["errorMessage"] = Error;
                return View("Index");
            }
       
        }


We will store all genres that we receive from DB in ViewData["genreList "]


Now in View:

@using (Ajax.BeginForm("UpdateMovieGenre", "Movie", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnFailure = "searchFailed", LoadingElementId = "ajax-loader", UpdateTargetId = "SearchResults", }))
 {




@Html.DropDownListFor(m=> m.genreID, new SelectList((System.Collections.IEnumerable)ViewData["genreList"], "id", "name"), new { @class = "Dropdown" })


<input type="submit" value="Update" class="submit_button" />

}

We use Ajax to submit form. In this case ajax accept 3 parameters(Action name, Controller name and AjaxOptions.


Please note that we create custom model and we passed it to controller. Custom model contains field genreID.
Let’s take a close look at DropDownListFor. First parameter is our model, second is SelectList which has to be IEnumerable. SelectList has 3 parameters – Collection that we passed, value that will be passed to controller(id), and display(name). The last parameter is html attribute which is optional.