gpt4 book ai didi

asp.net-mvc - 在 DropDownList 中验证所需的选择

转载 作者:行者123 更新时间:2023-12-03 13:28:33 26 4
gpt4 key购买 nike

我的 View 模型定义了必须显示为组合框的属性。属性定义为:

[Required]
public int Processor { get; set; }

我正在使用 DropDownListFor渲染组合框:
<%=Html.DropDownListFor(r => r.Processor, Model.Processors, Model.Processor)%>
Model.Processors包含 IEnumerable<SelectListItem>一个特殊项目定义为:
var noSelection = new SelectListItem
{
Text = String.Empty,
Value = "0"
};

现在我需要向我的组合框添加验证,以便用户必须选择不同的值,然后选择“noSelection”。我希望对 RequiredAttribute 进行一些配置但它没有默认值设置。

最佳答案

这个怎么样:

[Required]
public int? Processor { get; set; }

进而:
<%= Html.DropDownListFor(
x => x.Processor, Model.Processors, "-- select processor --"
) %>

在你的 POST Action 中
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (ModelState.IsValid)
{
// the model is valid => you can safely use model.Processor.Value here:
int processor = model.Processor.Value;
// TODO: do something with this value
}
...
}

现在您不再需要手动添加 noSelection元素。只需使用正确的 DropDownListFor重载。

关于asp.net-mvc - 在 DropDownList 中验证所需的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4672289/

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