如何从DropDownListFor列表中选择一个项目? (MVC3)

时间:2012-01-22 07:21:39

标签: asp.net-mvc-3 html.dropdownlistfor

我正在使用此代码填充下拉列表(并且工作正常):

@Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text"), "Please Select a Country")

有时,此视图还会获取预选国家/地区的数据,因此我想选择该国家/地区。

我试过了:

@Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text", "United States"), "Please Select a Country")

但是这没用。我也试过了这个项目的价值,但没有运气。

我做错了什么?

此外,有没有办法在创建后访问/修改该元素? (使用C#而不是javascript)

谢谢!

1 个答案:

答案 0 :(得分:3)

Model.Countries列表中有2个属性:TextValue。因此,如果您想在下拉列表中预先选择给定项目,则应使用以下值:

@Html.DropDownListFor(
    x => x.SelectedCountry, 
    new SelectList(Model.Countries, "Value", "Text", "us"), 
    "Please Select a Country"
)

假设在Model.Countries中有一个Value="us"的项目。

作为替代方法,您可以在返回视图的控制器操作中执行此操作:

public ActionResult Foo()
{
    var model = new MyViewModel();
    model.Countries = new[]
    {
        new SelectListItem { Value = "fr", Text = "France" },
        new SelectListItem { Value = "uk", Text = "United Kingdom" },
        new SelectListItem { Value = "us", Text = "United States" },
    };
    model.SelectedCountry = "us";
    return View(model);
}

在视图中你可以简单地说:

@Html.DropDownListFor(
    x => x.SelectedCountry, 
    Model.Countries, 
    "Please Select a Country"
)

将使用Value="us"(我的示例中的第三个)预选元素。