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

ASP.NET GridView客户端及服务端自定义验证失效问题求助

ASP.NET GridView 验证问题解决方案

客户端验证问题修复

问题根因

  • jQuery取值语法错误:val是方法需加括号调用,原代码ddl.val、text.val无法正确获取控件值
  • 变量赋值逻辑错误:声明文本框对象时直接赋值默认值,会强制覆盖用户已有输入
  • 死循环触发:alert弹出时会再次触发元素的focusout事件,加上强制回焦逻辑形成循环
  • 事件绑定失效:GridView动态渲染(回发、分页)后,直接绑定的事件会丢失,需用事件委托绑定到固定父元素

修正后代码

// 绑定到GridView的固定父容器,此处示例GridView ID为FormCGrid
$('#FormCGrid').on('focusout', 'select[name*="ddlCurrAdditions"]', function () {
    const ddl = $(this);
    if (ddl.val() === "-select curriculum name-") {
        setTimeout(() => {
            ddl.focus();
            alert("select a curriculum name before moving on");
        }, 10);
    }
});

$('#FormCGrid').on('focusout', 'input[name*="txtCurriculum"]', function () {
    const text = $(this);
    if (text.val() === 'enter lesson/unit name here') {
        setTimeout(() => {
            text.focus();
            alert('enter in a lesson or unit name before moving on');
        }, 10);
    }
});

// 仅在页面初始化时给空文本框设置默认值
$('#FormCGrid input[name*="txtCurriculum"]').each(function () {
    if ($(this).val() === '') {
        $(this).val('enter lesson/unit name here');
    }
});

服务端验证问题修复

触发失效排查项

  1. 给CustomValidator添加属性ValidateEmptyText="true",无关联ControlToValidate时必须开启才会触发验证
  2. 确认提交按钮的CausesValidation="true",且按钮和CustomValidator的ValidationGroup属性值一致
  3. 确认CustomValidator的OnServerValidate="cv1_ServerValidate"属性已正确绑定验证事件

逻辑优化说明

  • 初始化args.IsValid = true,避免默认状态异常
  • 下拉列表可见时追加判断选中值是否为默认值,避免误判
  • 错误信息拼接处理,避免多个行错误时提示被覆盖

修正后代码

protected void cv1_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = true;
    CustomValidator cv = (CustomValidator)source;
    cv.ErrorMessage = "";
    foreach (GridViewRow row in FormCGrid.Rows)
    {
        TextBox txtC = (TextBox)row.FindControl("txtCurriculum");
        DropDownList ddlCurr = (DropDownList)row.FindControl("ddlCurrAdditions");
        
        if (txtC != null && txtC.Text.Trim() == "enter lesson/unit name here")
        {
            args.IsValid = false;
            cv.ErrorMessage += $"行{row.RowIndex + 1}:请输入课程/单元名称<br/>";      
        }
        else if (ddlCurr != null && ddlCurr.Visible && ddlCurr.SelectedItem.Text == "-select curriculum name-")
        {
            args.IsValid = false;
            cv.ErrorMessage += $"行{row.RowIndex + 1}:请选择课程名称<br/>";
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 09:36:08