creating a drop down list in MVC5

user3541362 picture user3541362 · May 9, 2014 · Viewed 13.8k times · Source

I am trying to create a drop down list but it gives me an error saying 'Cannot implicitly convert type 'string' to 'System.Web.Mvc.SelectList'. My code is below:

Application Database Model:

public string dropdown{ get; set; }

Application View Model:

public SelectList dropdown{ get; set; }

ApplicationService.cs:

 public static SelectList GetDropdownList(string currSelection)
    {
        List<SelectListItem> list = new List<SelectListItem>();
        list.Add(new SelectListItem { Value = "1", Text = "firstvalue" });
        list.Add(new SelectListItem { Value = "2", Text = "secondvalure" });
        list.Add(new SelectListItem { Value = "3", Text = "All of the Above" });


        return new SelectList(list, "Value", "Text", currSelection);
    }

in my controller i am calling:

 applicationviewmodel.dropdown= ApplicationService.GetDropdownList(null);

 and then trying to save it in database as:

 ApplicationDatabaseModel.dropdown= applicationviewmodel.dropdown;

This is where i get this error.

In my view i have:

 @Html.DropDownListFor(x => x.dropdown, applicationviewmodel.dropdown)

I am not sure how to make this work.

Answer

MiiisterJim picture MiiisterJim · May 9, 2014

I find it's easier to just have a List as part of your model and use a simple linq statement. Simple example below for a countries drop down:

assuming you have a model like

public class MyModel()
{
    public int CountryId { get; set; }
    public List<Country> Countries { get; set; }
}

and a Country class of

public class Country()
{
    public int Id { get; set; }
    public string Name { get; set; }
}

in your view you can then do the following:

@Html.DropDownListFor(m => m.CountryId, 
                           Model.Countries.Select(x => 
                                new SelectListItem { Text = x.Name, Value = x.Id.ToString(), Selected = Model.CountryId == x.Id }, "Please Select...", null)