User987 User987 - 1 month ago 6
C# Question

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?

Answer

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)
Comments