Arianule
Arianule

Reputation: 9043

Adding a default value to selected list Razor

I am populating a dropdown like this

 primaryDrop = new Dictionary<string, string>()
            {
                {"1", "Getting ready"}, 
                {"2", "Starting"}, 
                {"3", "All"}, 
                {"4", "Other"}

            };
        PrimaryDrop = primaryDrop.Select(item => new SelectListItem
        {
            Value = item.Key,
            Text = item.Value
        });

And displaying it like this

@Html.DropDownListFor(m => m.SelectedPrimary, new SelectList(Model.PrimaryDrop, "Value", "Text"), "Select ...", new { @class = "form-control" })

How can I select a default value to 'Other' for example

Was thinking something like this

@Html.DropDownListFor(m => m.SelectedPrimary, new SelectList(Model.PrimaryDrop, "Value", "Text", new { SelectedItem = "Other" }), "Select ...", new { @class = "form-control" })

but doesn't work

Upvotes: 0

Views: 3659

Answers (2)

DavidG
DavidG

Reputation: 118937

You don't need to create an object to specify the selected item, you just need to give the value you want. In your case, Other has a value of 4:

@Html.DropDownListFor(m => m.SelectedPrimary, 
                      new SelectList(ViewBag.PrimaryDrop, "Value", "Text", "4"),
                      "Select ...", 
                      new { @class = "form-control" })

Upvotes: 1

Edward N
Edward N

Reputation: 997

You can achieve it by server code, when you populate data

PrimaryDrop = primaryDrop.Select(item => new SelectListItem
    {
        Value = item.Key,
        Text = item.Value,
        Selected = item.Key == "4" // Or item.Value== "Others"  
    });

Or we can set value for SelectedPrimary of model

SelectedPrimary = "4"

Upvotes: 1

Related Questions