模型绑定下拉列表选择的值

时间:2011-02-28 12:02:41

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

我有一个模型,该模型有一个public List<string> Hour { get; set; } 和构造函数

public SendToList()
    {
        Hour = new List<string> { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" };
    }

我的问题是为什么我没有为此

选择一个值
@Html.DropDownListFor(model => model.Hour, Model.Hour.Select( 
                x => new SelectListItem
                {
                    Text = x,
                    Value = x,
                    Selected = DateTime.Now.Hour == Convert.ToInt32(x)
                }
            ))

但我在这里得到一个选定的值。

@Html.DropDownList("Model.Hour", Model.Hour.Select( 
                x => new SelectListItem
                {
                    Text = x,
                    Value = x,
                    Selected = DateTime.Now.Hour == Convert.ToInt32(x)
                }
            ))

有什么区别?

1 个答案:

答案 0 :(得分:11)

因为您需要将所选值分配给模型。

所以我建议你采用以下方法。让我们从视图模型开始:

public class MyViewModel
{
    // this will hold the selected value
    public string Hour { get; set; }

    public IEnumerable<SelectListItem> Hours 
    { 
        get
        {
            return Enumerable
                .Range(0, 23)
                .Select(x => new SelectListItem {
                    Value = x.ToString("00"),
                    Text = x.ToString("00")
                });
        } 
    }
}

您可以在控制器中填充此视图模型:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            // Set the Hour property to the desired value
            // you would like to bind to
            Hour = DateTime.Now.Hour.ToString("00")
        };
        return View(model);
    }
}

在您看来简单:

@Html.DropDownListFor(
    x => x.Hour, 
    new SelectList(Model.Hours, "Value", "Text")
)