0

I want to add the "selected" property to one of the options in the drop down list based on the value to the option

    @Html.DropDownListFor(m => m.OvelseTypeId, new SelectList(Model.OvelseType, "Id", "navn"), "-- Please select --", new { @class = "form-control" }) 

I would image it to be something like (8 being the value)

    @Html.DropDownListFor(m => m.OvelseTypeId, new SelectList(Model.OvelseType, "Id", "navn").Select(8), new { @class = "form-control" }) 

or

    @Html.DropDownListFor(m => m.OvelseTypeId, new SelectList(Model.OvelseType, "Id", "navn"), 8, new { @class = "form-control" }) 

I have seen Html.DropDownListFor set selected value. But I just feel there has to be an easier way, as I simply just want to add selected to one of the options in the drop down list. Giving me What I want

Sondre
  • 105
  • 2
  • 11
  • 1
    Did you looking for [`SelectList` overload](https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.selectlist.-ctor?view=aspnet-mvc-5.2#System_Web_Mvc_SelectList__ctor_System_Collections_IEnumerable_System_String_System_String_System_Object_) which contains a parameter to set selected value? You could set it e.g. `new SelectList(Model.OvelseType, "Id", "navn", 8)`. – Tetsuya Yamamoto Mar 26 '19 at 03:01
  • 1
    Also since you're using `DropDownList` helper, you can't have more than one `selected` attribute for `select` element without `multiple` attribute. Alternatively you can convert `Model.OvelseType` to `List` and set `Selected` property from controller (`Selected = x.Id == SelectedValue`). – Tetsuya Yamamoto Mar 26 '19 at 03:25
  • 1
    Did you already read [this one](https://stackoverflow.com/questions/19476530/html-dropdownlistfor-selected-value-not-being-set) to set `SelectList` containing option lists into `DropDownList` helper? If you want to set default selected value, then assign it into fourth parameter of `SelectList` constructor. – Tetsuya Yamamoto Mar 26 '19 at 04:01
  • 1
    check this https://stackoverflow.com/questions/23799091/html-dropdownlistfor-how-to-set-default-value – Abhinaw Kaushik Mar 26 '19 at 05:04

0 Answers0