1

I'm populating a drop down list using this code (and it works fine):

@Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text"), "Please Select a Country")

Sometimes, this view also gets data of a pre-selected country, so I want to select that country.

I tried:

@Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text", "United States"), "Please Select a Country")

But this didn't work. I also tried the value of the item, and no luck.

What am I doing wrong?

Also, is there a way to access / modify that element after creation? (using C# not javascript)

Thanks!

Michael
  • 287
  • 1
  • 2
  • 10
  • 1
    Did you check this one? http://stackoverflow.com/questions/781987/how-can-i-get-this-asp-net-mvc-selectlist-to-work – Ofer Zelig Jan 22 '12 at 07:26
  • I can't find a clear answer there, can you direct me maybe to a specific place? I would rather avoid functions for this if possible. – Michael Jan 22 '12 at 07:39
  • I got it to work when the model contains the value of the selected item, it works. that is when: x.SelectedCountry has data (the value, not the text), it works. (with the same code as before) – Michael Jan 22 '12 at 08:43
  • can you post your `ActionResult` that is responsible for generating the said view – John x Jan 22 '12 at 09:45

1 Answers1

3

There are 2 properties in the Model.Countries list: the Text and the Value. So if you want to preselect a given item in the dropdown you should use the value:

@Html.DropDownListFor(
    x => x.SelectedCountry, 
    new SelectList(Model.Countries, "Value", "Text", "us"), 
    "Please Select a Country"
)

which assumes that in Model.Countries you have an item with Value="us".

As an alternative you could do this inside the controller action that is returning the view:

public ActionResult Foo()
{
    var model = new MyViewModel();
    model.Countries = new[]
    {
        new SelectListItem { Value = "fr", Text = "France" },
        new SelectListItem { Value = "uk", Text = "United Kingdom" },
        new SelectListItem { Value = "us", Text = "United States" },
    };
    model.SelectedCountry = "us";
    return View(model);
}

and in the view you could simply:

@Html.DropDownListFor(
    x => x.SelectedCountry, 
    Model.Countries, 
    "Please Select a Country"
)

which will preselect the element with Value="us" (the third one in my example).

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928