Setting a default selected value in DropDownList in MVC3

前端 未结 3 589
滥情空心
滥情空心 2021-01-11 18:55

In MVC3 I have this code at my controller. It retrieves a List of IDs\\Names from Installation table and creates a ViewBag

var vs = dba.Installation.OrderBy(         


        
相关标签:
3条回答
  • 2021-01-11 19:40

    You can also create an Helper class for Dropdownlist It will have a method to set the text as by default text for every dropdownlist in you solution

    0 讨论(0)
  • 2021-01-11 19:42

    I need to set first item in the ViewBag List as a default selected value, instead of "- Select one -" text.

    Then you need to select the first item in your list (vs) and get it's id and use it as the selecedValue in the SelectList:

    ViewBag.Vessels = new SelectList(vs, "InstId", "InstName", 
        vs.FirstOrDefault().InstId);
    
    0 讨论(0)
  • 2021-01-11 19:45

    There's an overload for the SelectList constructor that takes 4 arguments. The last of which is the default selected object. E.g:

    ViewBag.Vessels = new SelectList(vs, "InstId", "InstName", selectedValue);
    

    Where selectedValue is an object of whatever type is in your list.

    0 讨论(0)
提交回复
热议问题