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.
There are 2 ways:
null
, Because it's selected value.ViewBag.Districts = new SelectList(repoBPASFM.Map<DistrictDTOList>("GetDistrict"), "DistrictID", "DistrictName");
null
by the value that you want to defaultint selectedValue = 1;
ViewBag.Districts = new SelectList(repoBPASFM.Map<DistrictDTOList>("GetDistrict"), "DistrictID", "DistrictName", selectedValue);