无法获得MVC3 DDL SelectedValue工作

时间:2012-04-05 20:55:49

标签: asp.net-mvc-3 ddl selectedvalue

这是我的VM

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

使用我的控制器

    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);
        }
    }

最后是视图

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

Model.CurrentCountry是Code。

正确呈现DDL

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

但没有国家被选中,我缺少什么?

2 个答案:

答案 0 :(得分:1)

您应该将CurrentCountry道具设置为表达式,否则您也无法在表单提交中获得所选国家/地区。

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

答案 1 :(得分:0)

这有效......

而不是

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

用于

@Html.DropDownList(Model.CurrentCountry,
                   new SelectList(Model.Countries.ToList(),
                                  "Code", "Name", Model.CurrentCountry))