asp.net-mvcdropdownlistfor

Asp.Net MVC | Dropdownlist data extraction


How can I pull the relevant sql data into the dropdownlistfor control below? Dropdownlist should default to "m.alici" data.

 <div class="form-group">
            <label for="exampleInputEmail3">Müşteri Adı Soyadı</label>
            @Html.TextBoxFor(m => m.Alici, new { @class = "form-control" })
        </div>
        <div class="form-group">
            <label for="exampleInputPassword4">Sipariş Adresi</label>
            @Html.TextAreaFor(m => m.adres, new { @class = "form-control" })
        </div>
        <div class="form-group">
            <label for="exampleSelectGender">Sipariş Durumu</label>
            @Html.DropDownListFor(m=>m.Durum


        </div>

Solution

  • Create a ViewBag in your Controller. Note that the default value can be added to the last parameter.

     ViewBag.Example = new SelectList((from s in _cs.example.OrderBy(s => s.Code)
     select new { ID = s.Id, FullDescription = s.Code + " - " + s.Description }),"ID", 
    "FullDescription","m.alici");
    

    and then in your view

     @Html.DropDownListFor(m => m.Durum, (SelectList)ViewBag.Example, new { @class = "form-control" })