gpt4 book ai didi

asp.net-mvc - 模型绑定(bind)下拉选择值

转载 作者:行者123 更新时间:2023-12-04 17:04:49 24 4
gpt4 key购买 nike

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

有什么不同?

最佳答案

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

所以我会推荐你​​下面的方法。让我们从 View 模型开始:

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")
});
}
}
}

您可以在 Controller 中填充此 View 模型:
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")
)

关于asp.net-mvc - 模型绑定(bind)下拉选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5141714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com