Adding a default SelectListItem

后端 未结 7 1250
一整个雨季
一整个雨季 2020-12-28 18:33
 public IEnumerable GetList(int? ID)
 {
      return from s in db.List
             orderby s.Descript
             select new SelectListItem
          


        
7条回答
  •  星月不相逢
    2020-12-28 18:48

    As you are using ASP.NET MVC, you can do this in the view by specifying a value for the optionLabel parameter of the DropDownField method of the HtmlHelper - e.g:

    htmlHelper.DropDownList("customerId", selectList, "Select One");
    

    Putting this type of code in your UI layer is probably more appropriate than having it in the data layer. One downside to doing this is that your select box will have an empty string value, not a "0" for the 'Select One' option, but that is not really a problem as you can treat this as a null value if your controller action method can accept a nullable int for the relevant parameter - e.g.

    public ActionResult DoSomething(int? customerId)
    {
      if(customerId != null)
      {
        // do something with the value
      }
    }
    

提交回复
热议问题