gpt4 book ai didi

c# - 在 asp.net mvc 中,下拉列表值始终返回零

转载 作者:行者123 更新时间:2023-11-30 15:55:58 25 4
gpt4 key购买 nike

这是模型类的示例

[Required(ErrorMessage = "Department is required")]
[Display(Name = "Department")]
public int SelectedValue { get; set; }


[Required(ErrorMessage = "Department is required")]
[Display(Name = "Department")]
public List<Department> RoleList { get; set; }

这是 View

<div class="col-md-10">
@Html.DropDownListFor(m => m.RoleList, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })
@Html.ValidationMessageFor(model => model.SelectedValue, "",new { @class = "text-danger"})
</div>

该列表完全来自数据库。现在当我选择列表中的项目时,选择值必须发送到 Controller

public async Task<ActionResult> Register(RegisterViewModel model)
{
int Selectedvalue = model.SelectedValue;
if (ModelState.IsValid && (model.SelectedValue).ToString() != "0")
{

这里我做了一个选择

enter image description here

错误

enter image description here

最佳答案

你应该改变它

@Html.DropDownListFor(m => m.RoleList, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })

@Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })

DropDownListFor 的第一个参数应该是模型中的选定值。在您的情况下,此属性是 Model.SelectedValue 而不是 Model.RoleList

关于c# - 在 asp.net mvc 中,下拉列表值始终返回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47679411/

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