FaceLess No One
FaceLess No One

Reputation: 25

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.

Upvotes: 0

Views: 710

Answers (2)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14218

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

Upvotes: 1

NoOneJr
NoOneJr

Reputation: 52

You are specifying null instead of that could specify the DistrictID

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

Upvotes: 1

Related Questions