在DropDownList中选择一个值

时间:2011-10-15 16:31:08

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-2

我有以下声明:

<%: Html.DropDownList("dropCity", new[] { new SelectlistItem { Text = "City1", Value = 1}, new SelectlistItem { Text = "City2", Value = 2}, new SelectlistItem { Text = "City3", Value = 3}})%> 

我的控制器发送到包含此下拉列表的aspx页面的值为“3”的变量,如何设置此下拉列表以在页面加载时选择此选项?

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

如果您的控制器传递'3',为什么不让它通过SelectListItem的所有列表呢?

然后你会在控制器中做这样的事情:

public ActionResult MyController(MyModel model) 
{
    // Build SelectListItem list
    ViewBag.CitiesList = new List<SelectListItem>() 
    {
        new SelectlistItem { Text = "City1", Value = 1, Selected = true}, 
        new SelectlistItem { Text = "City2", Value = 2}, 
        new SelectlistItem { Text = "City3", Value = 3}
    }

    View(model);
}

并在视图中以这种方式接收:

<%: Html.DropDownList("dropCity", ViewBag.CitiesList as IEnumerable<SelectListItem>) %>

这样,选择合适城市背后的所有逻辑都在控制器中,从一开始就应该如此。

答案 1 :(得分:1)

使用视图模型:

public class MyViewModel
{
    public string SelectedCityId { get; set; }
    public IEnumerable<SelectListItem> Cities { get; set; }
}

然后让您的控制器填充此视图模型:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        // preselect the second city
        SelectedCityId = "2",
        Cities = new[]
        {
            new SelectListItem { Value = "1", Text = "City1" },
            new SelectListItem { Value = "2", Text = "City2" },
            new SelectListItem { Value = "3", Text = "City3" },
        }
    };
    return View(model);
}

最后在你的强类型视图中:

<%= Html.DropDownListFor(x => x.SelectedCityId, Model.Cities) %>

答案 2 :(得分:0)

创建selectlistitem时,只需执行以下操作:

new SelectlistItem { Text = "City1", Value = 1, Selected=true}

答案 3 :(得分:0)

<%: Html.DropDownList("dropCity", new[] { 
      new SelectlistItem { Text = "City1", Value = 1, Selected = true}, 
      new SelectlistItem { Text = "City2", Value = 2}, 
      new SelectlistItem { Text = "City3", Value = 3}})%> 
相关问题