0

I have a Drop Down List in my MVC application, which is populated from my "PropertyList" model.

I have set the propertyList variable as follows to obtain the details needed for each option as follows;

var propertyList = new SelectList(Model.propertyList, "fullPropertyDetail", "FullAddress");

@Html.DropDownList("addresslist", (SelectList)propertyList, "-- Please select an address from the list below --", new { @id = "valid-addresslist" })

This populates the list as expected and the default option reads "-- Please select an address from the list --", however the value for that option is set as "".

Is there any way I can set the default option value as "none" as another system looks for this value if it is selected.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
andtodd
  • 240
  • 1
  • 13
  • Possible duplicate of [@Html.DropDownListFor how to set default value](https://stackoverflow.com/questions/23799091/html-dropdownlistfor-how-to-set-default-value) – EzLo Feb 08 '19 at 10:06
  • 1
    @andtodd `Is there any way I can set the default option value as "none"` means? Please make it clear. – TanvirArjel Feb 08 '19 at 10:07
  • The default option displayed to the customer is "-- Please select an address from the list below --", i.e. that is the text they see, however the value of that item is set as "" (blank) and I need that value set as "none". – andtodd Feb 08 '19 at 10:09
  • Okay! got it. Please check my answer. it will work for you – TanvirArjel Feb 08 '19 at 10:16
  • Use my updated answer. I have made a mistake with `IsSelected` instead of `Selected`? – TanvirArjel Feb 08 '19 at 10:22
  • Thanks, this worked perfectly. – andtodd Feb 08 '19 at 10:50

2 Answers2

2

Simply you can do as follows:

@{
   List<SelectListItem> selectListItems = propertyList.ToList();
   selectListItems.Insert(0, (new SelectListItem { Text = "Please select", Value = "none", Selected = true }));
}
@Html.DropDownList("addresslist", selectListItems, new { @id = "valid-addresslist" })
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
0

Add the "-- Please select ..... below --"option as SelectListItem in the propertyList List.

Like: new SelectListItem { Text = "-- Please select ..... below --", Value = "none"}

Mike Bovenlander
  • 5,236
  • 5
  • 28
  • 47