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

MVC Razor数据注解与部分辅助工具失效求助

解决MVC Razor数据注解与验证工具失效问题

1. 确保引入客户端验证脚本

客户端验证依赖以下两个脚本,需在页面(或布局页)中引入(注意先引入jQuery核心脚本):

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

2. 检查Web.config验证配置

确认Web.config中已开启非侵入式验证和客户端验证:

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

3. 修正ValidationMessage用法

改用强类型的ValidationMessageFor,避免硬编码字段名出错:

@Html.ValidationMessageFor(c => c.baseNumber, null, new { @class = "text-danger" })

4. 修正模型数据注解逻辑

你的Range注解逻辑与错误提示不匹配,按字段类型调整:

  • 若baseNumber是字符串类型,改用长度+格式验证:
    [Required(ErrorMessage = "Base number is required.")]
    [Display(Name = "Base number")]
    [MinLength(7, ErrorMessage = "Value must be 7 characters long.")]
    [MaxLength(7, ErrorMessage = "Value must be 7 characters long.")]
    [RegularExpression(@"^[0-9.-]+$", ErrorMessage = "Only numbers, dots and hyphens are allowed.")]
    public string baseNumber { get; set; }
    
  • 若baseNumber是数值类型(如int/long),调整范围匹配7位数:
    [Required(ErrorMessage = "Base number is required.")]
    [Display(Name = "Base number")]
    [Range(1000000, 9999999, ErrorMessage = "Value must be a 7-digit number.")]
    public int baseNumber { get; set; }
    

5. 确保表单正确生成

使用MVC的Html.BeginForm生成表单,而非原生<form>标签,保证验证逻辑绑定:

@using (Html.BeginForm("YourAction", "YourController", FormMethod.Post))
{
    // 表单控件代码
}

6. 服务器端验证兜底

在控制器Action中添加模型状态校验,作为客户端验证的兜底:

[HttpPost]
public ActionResult YourAction(YourModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model); // 返回原页面显示验证错误
    }
    // 业务逻辑处理
    return RedirectToAction("Success");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:20:49