如果在DropDownListFor()中使用模型,则会错过选定的值

时间:2012-05-01 12:56:07

标签: c# asp.net-mvc-3 drop-down-menu

我遇到了这个DropDownListFor()

的问题

我有测试控制器:

model.COUNTRYNAME = "Swizerland";
        ViewBag.Selecter = new SelectList(new[]  
        { 
            new SelectListItem { Text = "USA", Value = "USA" }, 
            new SelectListItem { Text = "Swizerland", Value = "Swizerland", Selected =true}, 
             new SelectListItem { Text = "Russia", Value = "Russia" }, 

        }, "Text", "Value", model.COUNTRYNAME);

在视图

@Html.DropDownListFor(x => Model.COUNTRYNAME , (SelectList)ViewBag.Selecter)

DropDownListFor没有选择值,它总是选择第一个值。

有什么问题?

如果我使用DropDownList

@Html.DropDownList("COUNTRYNAME" , (SelectList)ViewBag.Selecter)

它也不起作用。

但如果我使用

@Html.DropDownListFor("AAAAAAA" , (SelectList)ViewBag.Selecter)

它工作正常并选择第二个值!怎么了?我不明白。

由于

1 个答案:

答案 0 :(得分:0)

试试这样:

model.COUNTRYNAME = "Swizeland";
ViewBag.Selecter = new[]  
{ 
    new SelectListItem { Text = "USA", Value = "USA" }, 
    new SelectListItem { Text = "Swizeland", Value = "Swizeland" },
    new SelectListItem { Text = "Russia", Value = "Russia" }, 
};
return View(model);

并在视图中:

@Html.DropDownListFor(
    x => x.COUNTRYNAME, 
    (IEnumerable<SelectListItem>)ViewBag.Selecter
)

但更好的方法是使用视图模型:

model.SelectedCountry = "Swizeland";
model.Countries = new[]  
{ 
    new SelectListItem { Text = "USA", Value = "USA" }, 
    new SelectListItem { Text = "Swizeland", Value = "Swizeland" },
    new SelectListItem { Text = "Russia", Value = "Russia" }, 
};
return View(model);

并在视图中:

@Html.DropDownListFor(x => x.SelectedCountry, Model.Countries)