can't get MVC3 DDL SelectedValue to work

Go To StackoverFlow.com

0

This is my VM

    public class CountriesViewModel
    {
        public string CurrentCountry { get; set; }
        public IEnumerable<Country> Countries { get; set; }
    }

With my Controller

    public class FiltersController : Controller
    {
        public ActionResult _ShipToCountry(IEnumerable<Country> countries,
                                           string currentCountry = "AE")
        {
            var viewModel = new CountriesViewModel
            {
                Countries = countries.OrderBy(x => x.Name),
                CurrentCountry = currentCountry
            };

            return PartialView(viewModel);
        }
    }

And finally the View

@Html.DropDownListFor(x => x.Countries,
                      new SelectList(Model.Countries.ToList(),
                                     "Code", "Name", Model.CurrentCountry))

Where Model.CurrentCountry is the Code.

The DDL is rendered correctly

...
<option value="UA">Ukraine</option>
<option value="AE">United Arab Emirates</option>
<option value="UK">United Kingdom</option>
....

But no Country gets selected, what am I missing?

2012-04-05 20:55
by kooshka
@kooshka...looks right. Are you sure "AE" is in the "Code" list for countrie - MikeTWebb 2012-04-05 21:11
"AE" is just the default it is on the list for sure. But any other country code that is passed, and it is passed I can see it when debugging, still doesn't select the DD - kooshka 2012-04-05 21:14


1

You should set CurrentCountry prop to expression if not also you cannot get the selected country on form submit.

@Html.DropDownListFor(x => x.CurrentCountry,
                      new SelectList(Model.Countries.ToList(), "Code", "Name"))
2012-04-06 08:58
by Yorgo
You're right, thanks - kooshka 2012-04-06 09:02


0

This worked...

Instead of

@Html.DropDownListFor(x => x.Countries,
                      new SelectList(Model.Countries.ToList(), 
                                     "Code", "Name", Model.CurrentCountry))

Used

@Html.DropDownList(Model.CurrentCountry,
                   new SelectList(Model.Countries.ToList(),
                                  "Code", "Name", Model.CurrentCountry))
2012-04-06 08:51
by kooshka
Ads