模型绑定下拉选择值

2024-04-06

我有一个模型,该模型有一个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)
                }
            ))

有什么不同?


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

所以我会向您推荐以下方法。让我们从视图模型开始:

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")
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

模型绑定下拉选择值 的相关文章

随机推荐