0

我遇到了这个 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)

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

谢谢

4

1 回答 1

1

试试这样:

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)
于 2012-05-01T12:58:10.040 回答