0

I already got the default value and the value already became the default, but the default value has no highlight or focus in the dropdown list.

I am using SelectItemList function.

Controller:

private List<SelectListItem> SelectWeek() {
    using(var db = new UsersContext()) {
        int currentYear = DateTime.Now.Year;
        selectListItems = db.WorkWeekDetails
            .Where(item = >item.YEAR == currentYear).OrderBy(item = >item.WORKWEEK)
            .Select(a = >new SelectListItem() {
                Text = a.WORKWEEK,
                Value = a.WORKWEEK
        }).ToList();

        selectListItems.Insert(0, new SelectListItem() {
            Text = www,  //www = "WW13"
            Value = www, //www = "WW13"
            Selected = true
        });
    }
    return ViewBag.WorkWeek = selectListItems;
}

CSHTML:

@Html.DropDownList("WorkWeek", (List<SelectListItem>)ViewBag.WorkWeek, new { @class = "form-control", required = "required" })

I want "WW13" to be the default value and that value to be highlighted in the dropdown list.

//Example list of dropdownlist :

WW13 // This value will be the default.
ww01
ww02
ww03
ww04
ww05
ww06
ww07
ww08
ww09
ww10
ww11
ww12
ww13 // This value will be highlighted.
ww14
...

Dropdown list:

[dropdown list]

karel
  • 5,489
  • 46
  • 45
  • 50
airalee
  • 1
  • 2
  • Possible duplicate of [Html.DropdownListFor selected value not being set](https://stackoverflow.com/questions/19476530/html-dropdownlistfor-selected-value-not-being-set) – Max Vollmer Mar 25 '19 at 04:35
  • The value already become default but no highlight at the dropdown – airalee Mar 25 '19 at 04:45
  • use jquery and when the page is loaded, find the select by name or id and find the selected option and apply CSS. – Aarif Mar 25 '19 at 07:30
  • Aarif thank you for respond. But can you show me some example, because I am not familiar with this language. – airalee Mar 25 '19 at 08:13

1 Answers1

0

As @Aarif said you can use jquery to hightlight the selected option... something like this

Also I think you should probably pass your drop down list through a View model rather than a viewbag

window.onload = function() {
highlightSelected()
};
function highLightSelected(){

    var model = @Html.Raw(Json.Encode(ViewBag.WorkWeek));

     foreach(var item in model){
         if(item.selected == true){
         $("#mydropdownlist").val(item.value);
         $("#mydropdownlist").addClass('active');
        }
    }
}

The syntax might not be exact but the idea is to check your list of SelectedListItem to find the one that is selected and set the drop list's value to that and also add the class which will highlight the selected value, but remember to remove this class on change of the dropdownlist value

Rennnn
  • 85
  • 9