DropdownListFor default value

前端 未结 5 512
無奈伤痛
無奈伤痛 2020-11-28 06:38

Is there a simple way to add a \"--Please select--\" default option to a DropDownListFor in MVC 3?

5条回答
  •  遥遥无期
    2020-11-28 07:13

    Hi what about trying this (in case you use DisplayFor method)

    private IEnumerable AddDefaultOption(IEnumerable list, string dataTextField, string selectedValue)
        {
            var items = new List();
            items.Add(new SelectListItem() { Text = dataTextField, Value = selectedValue});
            items.AddRange(list);
            return items;
        }
    

    Then just add this code to your Controller

    //lambda expression binding
    ViewBag.YourList = db.YourTable.Select(x => x).ToList().Select(x => new SelectListItem
            {
                Value = x.Id.ToString(),
                Text = x.DisplayName.ToString()
            });
    
            ViewBag.YourList = AddDefaultOption(ViewBag.YourList, "Select One...", "null", true);
    

    And finally at the View you could display a dropdown, combobox just like this

        
    Your Label
    @Html.DropDownListFor(model => model.ForeignKey, (IEnumerable)ViewBag.YourList)

提交回复
热议问题