【问题标题】:can't get MVC3 DDL SelectedValue to work无法让 MVC3 DDL SelectedValue 工作
【发布时间】:2012-04-05 20:55:49
【问题描述】:

这是我的虚拟机

    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 是代码。

DDL 渲染正确

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

但是没有国家被选中,我错过了什么?

【问题讨论】:

  • @kooshka...看起来不错。您确定“AE”在国家/地区的“代码”列表中吗
  • "AE" 只是默认值,它肯定在列表中。但是任何其他国家代码都通过了,并且通过了我调试的时候可以看到,仍然没有选择DDL

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这行得通...

    代替

    @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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多