adam78
adam78

Reputation: 10068

Asp MVC Dropdown List Selected Value not selected

I have the following dropdown list but the selected value doesn't seem to working. It defaults to first item in list.

    private List<string> GetTransmissions()
    {
        List<string> Transmission = new List<string>();
        Transmission.Add("Automatic");
        Transmission.Add("Manual");


        return Transmission;
    }

     Car car = _repository.GetCarDetails(id);

     ViewBag.Transmission = new SelectList(GetTransmissions(), car.Transmission);

In my view I have:

    @Html.DropDownList("Transmission", (IEnumerable<SelectListItem>)ViewBag.Transmission, "Please Select", new { @class = "form-control" })

Upvotes: 2

Views: 4248

Answers (3)

adam78
adam78

Reputation: 10068

Managed to fix by changing

 ViewBag.Transmission = new SelectList(GetTransmissions(), car.Transmission);

To

 ViewBag.Transmissions = new SelectList(GetTransmissions(), car.Transmission);

The Car model already contains an attribute called Transmission so need need for another ViewBag to hold this attribute.

In the my razor code use the following instead

  @Html.DropDownList("Transmission", (IEnumerable<SelectListItem>)ViewBag.Transmissions, "Please Select", new { @class = "form-control" })

Upvotes: -1

hutchonoid
hutchonoid

Reputation: 33306

If you are restricted to using ViewBag rather than a View Model and an @Html.DropDownList Html Helper then I would do the following:

        ViewBag.Transmissions = new SelectList(GetTransmissions()
        .Select(t => new {value = t, text = t}), 
            "value", "text");
        ViewBag.Transmission = car.Transmission;

The above creates the SelectList, then projects so that your dropdown renders text and values. This is saved in the ViewBag.Transmissions, which is the available options.

Then set your selected transmission with ViewBag.Transmission.

Your razor code would also need to be changed to use ViewBag.Transmissions too:

@Html.DropDownList("Transmission", 
      (IEnumerable<SelectListItem>)ViewBag.Transmissions, 
         "Please Select", new { @class = "form-control" })

Working Fiddle

Upvotes: 1

DaniCE
DaniCE

Reputation: 2421

You need to differentiate the property that holds the list and the property that holds the selected value.

I recommend using a viewmodel for the view like this:

public class CarViewModel
{

    public SelectList Transmissions
    {
        get
        {
            return new SelectList(new List<SelectListItem>{
                new SelectListItem {  Value = "Manual"},
                new SelectListItem {  Value = "Automatic"}
            });                
        }
    }

    public string Transmission { get; set; }

}

and use this DropDownListFor version

 @Html.DropDownListFor(model => model.Transmission,
    @Model.Transmissions, "Please Select", new { @class = "form-control" })

Upvotes: 2

Related Questions