gpt4 book ai didi

c# - 如何从下拉列表中获取选定的值

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

我正在绑定(bind)模型中的下拉列表,但无法从下拉列表中获取选定的值,它显示错误:

The value '1' is invalid , while submitting the form

模型代码

[Display(Name="User Type")]
[Required(ErrorMessage = "Select user type")]
public List<SelectListItem> usertype { get; set; }

查看代码

@Html.DropDownListFor(m => m.usertype, Model.usertype, new {  @class="form-control input-lg"})

Controller 代码

//controller
[HttpPost]
public ActionResult Register(Register register,FormCollection form)
{
}

填充下拉列表

[HttpGet]
public ActionResult Register()
{
var model=new Register();
List<string> stState = new List<string>();
List<SelectListItem> selectListItemStates = new List<SelectListItem>();
selectListItemStates.Add(new SelectListItem() { Value = string.Empty, Text = "Select State" });
selectListItemStates.Add(new SelectListItem() { Value = "1", Text = "Mentor" });
selectListItemStates.Add(new SelectListItem() { Value = "1", Text = "Employee" });
selectListItemStates.Add(new SelectListItem() { Value ="1", Text = "Finance" });


model.usertype = selectListItemStates.ToList();
return View(model);
}

最佳答案

您需要在模型中为 SelectedValue 添加一个属性,它很可能是 int

当前您正在将 DropDownListForSelectList 绑定(bind),这是不正确的,DropDownListFor 将发布选定的单个值,通常是整数:

    public List<SelectListItem> usertype { get; set; }

[Display(Name="User Type")]
[Required(ErrorMessage = "Select user type")]
public int UserType { get; set; }

在 View 中:

@Html.DropDownListFor(m=>m.UserType,Model.usertype, new {  @class="form-control input-lg"}

关于c# - 如何从下拉列表中获取选定的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29545377/

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