【发布时间】:2019-03-20 12:55:09
【问题描述】:
我在我的一个项目中使用这个问题的答案中的 javascript:
Adding Hyperlinks to ValidationSummary
它真的很棒。我已将它添加到我的母版页的底部(出于某种原因,即使它在 $(document).ready 中,如果我将它放在 head 部分中,Page_Validators 也是空的)
无论如何!我还使用此代码在回发时以编程方式添加了一些自定义验证器:
public static CustomValidator ReturnErrorMessage(string message, string validationGroup, string controlToValidate = "")
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ErrorMessage = message;
control.ControlToValidate = controlToValidate;
return control;
}
但是,每当我添加这样的 CustomValidator 时,在按钮事件、page_load 或其他任何事件中,Page_Validators 将被覆盖,并且错误消息将恢复为没有锚点的消息。
什么给了?我做错了什么还是有人可以解释发生了什么?
我试过调试它,它确实设置了正确的值,但之后它只是重置了。
我已经尝试过了,在 $(document).ready 中将所有验证器设置为 isvalid = false,这也会被覆盖。
我正在使用 asp.net 4.5 不显眼的验证,但如果我关闭它并没有什么不同。
在创建验证器后的某个时间点使用 Page.ClientScript.RegisterStartupScript 在代码中添加 javascript 也不起作用。
如果我不在代码中添加任何验证器,一切都会按预期工作。
我知道我可以手动添加锚标记,但要更新现有验证器而不是仅仅折腾一个小脚本需要做很多工作,所以我希望它能够工作。
您可以使用此代码进行测试:
using System;
using System.Web.UI.WebControls;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + txtName.ClientID;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = "errorGroup";
control.ErrorMessage = "Error message";
control.ControlToValidate = txtName.ClientID;
Form.Controls.Add(control);
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:ValidationSummary ID="vsSummary" runat="server" ValidationGroup="errorGroup" ForeColor="Red" HeaderText="Error!" />
</div>
</form>
<script>
$(document).ready(function() {
var validators = Page_Validators; // returns collection of validators on page
$(validators).each(function() {
//get target control and current error validation message from each validator
//[0] is needed when using aspnet 4.5 unobtrusive validation
var validator = $(this)[0];
var errorMsg = validator.errormessage;
var targetControl = validator.controltovalidate;
//make link only if theres a control to target
if (targetControl) {
var errorMsgWithLink = "<a href='#" + targetControl + "' style='color: #FF3232;'> " + errorMsg + "</a>";
//update error message with anchor tag
validator.errormessage = errorMsgWithLink;
}
});
});
</script>
</body>
</html>
【问题讨论】:
标签: javascript jquery html asp.net validation