Steve
Steve

Reputation: 352

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.

Upvotes: 0

Views: 7022

Answers (2)

Alex Art.
Alex Art.

Reputation: 8781

If you have a model with Status property then simply assign this the value to the property (for example in controller):

Model

public class Model
{

    public string Status {get;set;}
} 

Controller

public ActionResult SomeAction()
{
    //the value has to correspond to the Value property of SelectListItems
    //that you use when you create dropdown
    //so if you have new SelectListItem{ Text="Active", Value = "Active" }
    //then the value of Status property should be 'Active' and not a 0
    var model = new Model{Status = "Active"}

    return this.View(model);
}

View:

@model Model


@Html.DropDownListFor(m=>m.Status,new List<SelectListItem> { new SelectListItem{ Text="Active", Value = "Active" },new SelectListItem{ Text="InActive", Value = "InActive" }}, new { @class = "form-control" })

Upvotes: 1

teo van kot
teo van kot

Reputation: 12491

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> 

Upvotes: 1

Related Questions