You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC中ViewBag填充下拉列表默认值验证失效求助

解决ASP.NET Core MVC下拉列表验证不生效问题

1. 修正模型验证规则

显式配置[Required]属性禁止空字符串,同时添加自定义错误提示,确保空值提交时触发验证:

public class myClass
{
    [StringLength(250)]
    [Required(AllowEmptyStrings = false, ErrorMessage = "请选择午餐选项")]
    public string lunch { get; set; } = string.Empty;
}

2. 修复控制器语法错误并避免命名冲突

原控制器中存在语法错误,同时重命名ViewBag的键名,避免和模型属性lunch冲突:

public IActionResult Create()
{
    List<SelectListItem> lunchItems = new List<SelectListItem>
    {
        new SelectListItem{Value="No lunch", Text="No lunch"},
        new SelectListItem{Value="Turkey Sandwitch", Text="Turkey Sandwitch"}, // 补充缺失的逗号
        new SelectListItem{Value="Vegie Sandwitch", Text="Vegie Sandwitch"}
    };

    lunchItems.Insert(0, new SelectListItem { Value = string.Empty, Text = "Select" });

    ViewBag.LunchOptions = lunchItems; // 重命名ViewBag键,避免与模型属性名冲突

    return View();
}

3. 改用强类型下拉列表绑定(关键修复)

替换弱类型的DropDownList为强类型DropDownListFor,确保表单值与模型属性正确绑定:

<div class="form-group">
    <label asp-for="lunch" class="control-label"></label>
    @Html.DropDownListFor(m => m.lunch, ViewBag.LunchOptions as IEnumerable<SelectListItem>, new { @class = "form-control" })
    <span asp-validation-for="lunch" class="text-danger"></span>
</div>

4. 确保客户端验证正常启用

在视图或布局页中引入客户端验证脚本(ASP.NET Core默认模板已包含,需确认未缺失):

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

5. 完善POST方法的验证逻辑

提交表单时检查模型状态,验证失败需重新填充ViewBag并返回视图:

[HttpPost]
public IActionResult Create(myClass model)
{
    if (!ModelState.IsValid)
    {
        // 重新填充下拉列表选项
        List<SelectListItem> lunchItems = new List<SelectListItem>
        {
            new SelectListItem{Value="No lunch", Text="No lunch"},
            new SelectListItem{Value="Turkey Sandwitch", Text="Turkey Sandwitch"},
            new SelectListItem{Value="Vegie Sandwitch", Text="Vegie Sandwitch"}
        };
        lunchItems.Insert(0, new SelectListItem { Value = string.Empty, Text = "Select" });
        ViewBag.LunchOptions = lunchItems;

        return View(model);
    }

    // 执行表单提交后的业务逻辑
    return RedirectToAction("Index");
}

核心问题说明

  • 原代码中ViewBag.lunch与模型属性lunch同名,导致绑定逻辑混淆,重命名ViewBag键即可解决。
  • 弱类型DropDownList容易出现绑定偏差,强类型DropDownListFor能确保表单值与模型属性准确映射。
  • 模型初始化的string.Empty不影响验证,用户提交空值时,模型绑定后的值仍为空字符串,会触发[Required(AllowEmptyStrings = false)]的验证规则。

内容的提问来源于stack exchange,提问作者user788448

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 09:10:35