Using the DropDownList Helper in ASP.NET MVC - Pt 1 - Movie Store Setup

Ok, so I wanted to learn more about DropDownList Helpers in ASP.NET MVC, and Categories and Enums...Oh, my! I started going through this tutorial by Rick Anderson on MSDN here. Granted, it is over 6 years old now and targets MVC 3, but I figured it was still relevant (currently MVC 6) and I could update his instructions while I went along. Well, it turns out, he left out a lot of stuff in his tutorial and I thought I'd make note of it here, mainly for myself as a reference, and since comments are closed on his blog. So here goes...

In the first part of his tutorial, he went through explaining what the Dropdown helper is, and how to create a simple example. I'm not going to go into that here, it was a pretty straightforward explanation and you can follow the link to go through it yourself. The main gist of it is that the DropDownList Helper requires an IEnumerable<SelectListItem> (which inherits from a SelectList) or just a plain old List<SelectListItem> which as we all know, Lists can be enums. One thing that made it confusing is his sample code and List is Movie genres and he even calls the DropDownList "MovieType" but the whole project is a Music Store app and all the screenshots are of a Music Store site. Just made it all the more confusing. Guess somebody didn't check their work or didn't care, but I managed to muddle through.

Step 1: So, I set up my Models for the Movie, Genre, and Director entities I will need for the database. I learned the Code First way of creating data-driven applications with the Entity Framework, so I created my model classes first using the following schema:

Then, I created my DBContext class and enabled migrations and the Entity Framework created my database for me. I used SQL Server Express 2014 because I wanted to create a database diagram in SQL Server Management Studio (SSMS). It is just easier for me to visualize the database. To connect to SQL Server Express 2014 in Visual Studio and your application, it is as follows

    <add name="DefaultConnection" connectionString="Data Source=KATHERINE-ALIEN\SQLEXPRESS;Initial Catalog=MvcMovieStoreApp;Integrated Security=True"
      providerName="System.Data.SqlClient" />

Replace "KATHERINE-ALIEN" with whatever your machine name is, you can get your machine name on Windows by right-clicking  the Window icon in the left corner of your desktop. Then, click System and under Device Specifications you will see your device name.

Step 2: Create a MovieManager Controller. Right click on the Controllers folder, then Add > Controller... Select the "MVC 5 Controller with views, using Entity Framework" Click Add.


Model class: Movie
Data context class: MvcMovieStoreDb (or whatever your DBContext class is named)
Generate Views: Yes
Use a layout page: Yes
Controller name: MovieManagerController

The Entity Framework will create the action methods and views that we need to Create, Edit, Update, and Delete a Movie from the database.

Step 3: Under the Views folder, Open the MovieManager\Index.cshtml Razor view file...
Build and Run (Ctrl + F5) the application. If you seeded the database with data, or entered your data in the database using SSMS, you should see a table listing all the movies in your database. You can see what I added here.

Ok, now comes the fun part, we are going to add the DropDownList helper to the Edit View. We are going to create 2 Partial views, Choose Genre and Choose Director. We can reuse these in the Create View.

Step 4: Add a partial view to the Views > MovieManager folder by right-clicking on the MovieManager folder, Add > View (Be sure to select partial view), call it _ChooseGenre. 
View Name: _ChooseGenre
Template: Empty
Model Class: Movie
Click Add.

Add the following code to the _Choose Genre view.

<div class="editor-label">
    @Html.LabelFor(model => model.GenreId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
    @Html.DropDownList("GenreId", ViewBag.Genres as SelectList, String.Empty)
    @Html.ValidationMessageFor(model => model.GenreId, "", new { @class = "text-danger" })

Then, replace the Genre textbox with the Html.Partial line of code in the Edit.cshtml view as follows:


Follow the same steps above to create a Partial view for _ChooseDirector.

Step 4: Refactor the Create action method to fill the select list with Genres and Directors from the database. We are going to create a method in the MovieManagerController that we can call and reuse to fill the DropDownLists with data from the database. In the MovieManagerController, add the following method to the top of the controller.

private void SetGenreDirectorViewBag(int? GenreId = null, int? DirectorId = null)
            if (GenreId == null)
                ViewBag.Genres = new SelectList(db.Genres, "GenreId", "Name", GenreId);
            } else
                ViewBag.Genres = new SelectList(db.Genres.ToArray(), "GenreId", "Name", GenreId);
            if (DirectorId == null)
                ViewBag.Directors = new SelectList(db.Directors, "DirectorId", "Name");
            } else
                ViewBag.Directors = new SelectList(db.Directors, "DirectorId", "Name", DirectorId);

Now, we can call this method in the Get action method for Create(). and the Post action method for Create.

Step 5: in the GET: MovieManager/Create action, add the following line of code:

// GET: MovieManager/Create
        public ActionResult Create()
            return View();



Add comment