0

I have the below code that I use to populate my dropdown in my Razor Page I want to preselect a description - the "Value" of that needs to be set is found in

s.UserEstablishmentId

How can I preselect this on the dropdown

@Html.DropDownList("drpEstablishments",
                    getEstablishments().Select(s => new SelectListItem()
                        {

                          Text = s.Description,
                          Value = s.EstablishId.ToString()
                      }),
                     new
                     {
                         @class = "dropdown form-control"
                     })
AShah
  • 846
  • 2
  • 17
  • 33
  • Take a look at this link: https://stackoverflow.com/questions/23799091/html-dropdownlistfor-how-to-set-default-value you can find your answer here. – Shant Mar 02 '19 at 12:37
  • thats using preset options Im taking min from a database - finding it difficult to extrapolate from those examples – AShah Mar 02 '19 at 15:58

2 Answers2

1

You're using linq to create a new SelectListItem for getEstablishments element. When creating each instance of a SelectListItem() you need to determine if Selected should be true or false. Simply replace YourConditionForSelectionHere with a method that returns a bool or syntax that returns a bool, shown below:

@Html.DropDownList("drpEstablishments",
                    getEstablishments().Select(s => new SelectListItem()
                        {
                          Selected = (YourConditionForSelectionHere),
                          Text = s.Description,
                          Value = s.EstablishId.ToString()
                      }),
                     new
                     {
                         @class = "dropdown form-control"
                     })
PaulBinder
  • 2,022
  • 1
  • 16
  • 26
0

in the end something like this worked

 Selected= (s.UserEstablishmentId==s.EstablishId)? true:false,
AShah
  • 846
  • 2
  • 17
  • 33