当关联的requiredfieldvalidator(ASP.Net)触发后,我希望页面滚动到控件。我已经分别测试了所有代码段,并且它们都工作正常。但是,当我将它们组合到WebForm_OnSubmit()中时,无法找到要验证的控件。该代码仅找到一些始终具有以下属性的对象:
Validators,__ browserLink_sourceMapping
我不知道这意味着什么或为什么发生。谁能指出我在代码中的错误?
我尝试使用JS和jQuery查找要验证的控件,但是它们都产生相同的对象。
这是代码
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) {
for (var i in Page_Validators) {
//Verify it's the correct validation group & it's a triggered validation ctrl
try {
if (Page_Validators[i].validationGroup == "MyValidationGrp" && !Page_Validators[i].isvalid) {
//I've used these lines just to verify it's finding the correct control ID value before trying to get the control. Both this and the jQuery below yield the same result
//var ControlToScrollToId = Page_Validators[i].controltovalidate;
//var ControlToScrollTo = document.getElementById(ControlToScrollToId);
//I've used this code to look at the properties of the object:
//alert(ControlToScrollToId + " properties: " + Object.getOwnPropertyNames(ControlToScrollTo));
var control = $("#" + Page_Validators[i].controltovalidate);
var top = control.offset().top;
$('html, body').animate({ scrollTop: top - 10 }, 800);
control.focus();
break;
}
} catch (e)
{
console.error("Failed to scroll to validating control." + e.message);
break;
}
}
return false;
}
return true;
}
由于“ top”的值始终为零,因此代码始终总是滚动到页面顶部。这就是为什么我后退检查对象及其属性的原因,这就是我被卡住的原因。
答案 0 :(得分:0)
根本原因:该问题似乎与以下事实有关:我使用的某些控件的类为“ d-none”(Bootstrap 4x)。当存在该类时,代码的行为如我上面指出的那样。但是,如果我将类更改为“不可见”,则一切正常。我仍然想知道这是否是唯一的“解决方案”,还有更好的方法可以做到这一点。
哦,我没有使用隐藏字段,因为ASP.net验证程序无法使用它。