Search code examples
asp.net-mvcdropdownlistfor

How to show selected value in DropDownList of MVC


Below is my DropDownList in view

<div class="col-xs-8 col-sm-8 col-md-4">                           
 @Html.DropDownList("Status",new List<SelectListItem> { new SelectListItem{ Text="Active", Value = "Active" },new SelectListItem{ Text="InActive", Value = "InActive" }}, new { @class = "form-control" })
</div> 

From DB value is coming either as "Active" or "Inactive" and dropdown has already these two value. And from my DB i'm assigning value in ViewBag.IsStatus. Now suppose my value is coming "InAactive" from DB then how to assign this as Selected value in Dropdown rather than to show First dropdown by default as selected.


Solution

  • It's better to use DropDownListFor if you using MVC. But for your case just create SelectList and pass it to DropDownList. SelectList contructor has overload for selected value:

    @{ //theese lines actually should be in controller.
     var list = new List<SelectListItem> 
                 { 
                 new SelectListItem 
                       { 
                           Text="Active", 
                           Value = "0" 
                       }
                 ,new SelectListItem
                       { 
                           Text="InActive", 
                           Value = "1" 
                        }
                 }
    }
    
    //thats your code
    <div class="col-xs-8 col-sm-8 col-md-4">                           
       @Html.DropDownList("Status",new SelectList(list, "Value", "Text", ViewBag.IsStatus), new { @class = "form-control" })
    </div>