Asp MVC Dropdown List Selected Value not selected

℡╲_俬逩灬. 提交于 2021-02-10 05:48:11

问题


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" })

回答1:


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" })



回答2:


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




回答3:


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" })


来源:https://stackoverflow.com/questions/31295193/asp-mvc-dropdown-list-selected-value-not-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!