Search code examples
htmlasp.net-mvcdropdown

html dropdownlist load first value


Controller

 ViewBag.Districts = new SelectList(repoBPASFM.Map<DistrictDTOList>("GetDistrict"), "DistrictID", "DistrictName", null);

HTML

   <div class="col-lg-4">
        <label>
            District
        </label>
        <span class="text color-red">
            *
        </span>
        @Html.DropDownList("DistrictName", ViewData["Districts"] as SelectList,  new { @class = "form-control", @required = "required" })
    </div>

I have this code above working fine it shows all the data in the dropdown. But I am having a problem, I want to auto-select the first item in the dropdown list upon loading the page. My original code is @Html.DropDownList("DistrictName", ViewData["Districts"] as SelectList,"", it has a blank white space in the selection and I thought if I remove it it will auto-select the first item of the dropdown.


Solution

  • There are 2 ways:

    1. You should remove the last param null, Because it's selected value.
    ViewBag.Districts = new SelectList(repoBPASFM.Map<DistrictDTOList>("GetDistrict"), "DistrictID", "DistrictName");
    
    1. You should replace the last param null by the value that you want to default
    int selectedValue = 1;
    ViewBag.Districts = new SelectList(repoBPASFM.Map<DistrictDTOList>("GetDistrict"), "DistrictID", "DistrictName", selectedValue);
    

    Demo here