User987
User987

Reputation: 3823

Setting up properly DropDownListFor in MVC 5

I use a ADO.NET Entity framework to map my DB into Model in my application. I've setup my ViewModel for registration like following:

public class UserRegistrationViewModel
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string PasswordConfirm { get; set; }
        public SelectList Countries { get; set; }

    }

The specific part here is that I want to fill up my dropdown list with Countries from my DBContext which looks like this:

Connection.ctx.Countries.OrderBy(x => x.CountryName).ToList();

As you can see the countries are a list now, and in my view I would like to set up a dropdown list using Html helper class like this:

  @Html.DropDownListFor(model => model.Countries);

And this is how I've mapped my model in the view:

@model WebApplication2.ViewModels.UserRegistrationViewModel

How do I properly setup the dropdown list (i.e. select list) so that I can display data from the DB?

Upvotes: 2

Views: 136

Answers (2)

ocuenca
ocuenca

Reputation: 39326

Add a property in your viewModel to save the id of selected country:

public class UserRegistrationViewModel
{
    //
    public int SelectedCountryId { get; set; }
    public SelectList Countries { get; set; }

}

I'm going to guess at the time to set Countries property you are doing something like this:

var countries=Connection.ctx.Countries.OrderBy(x => x.CountryName).ToList();
//...
viemodel.Countries=new SelectList(countries, "CountryId", "CountryName");

Then in your view you can do the following:

@Html.DropDownListFor(model => model.SelectedCountryId, Model.Countries)

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239240

You need two properties: one to hold the selected value and one to hold your select list options:

public string Country { get; set; }

public IEnumerable<SelectListItem> CountryOptions { get; set; }

Then, in your view:

@Html.DropDownListFor(m => m.Country, Model.CountryOptions)

You don't need an actual SelectList. In fact, it's preferable if you don't. Razor will automatically create a SelectList and select the appropriate value.

Upvotes: 2

Related Questions