Page.IsValid 如何工作? [英] How does Page.IsValid work?

查看:22
本文介绍了Page.IsValid 如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下带有 RequiredFieldValidator 的代码.EnableClientScript 属性在验证控件中设置为false".另外我在浏览器中禁用了脚本.

我没有在后面的代码中使用 Page.IsValid.尽管如此,当我在文本框中没有任何值的情况下提交时,我会收到错误消息.

从@Dai 的评论中,我知道这可能是一个问题,如果 Page_Load 中有任何代码在 postback 中执行.不会抛出任何验证错误.

(但是,对于按钮点击处理程序,不需要检查Page.IsValid)

if (Page.IsPostBack){字符串值 = txtEmpName.Text;txtEmpName.Text = value + "Appended";}

问题

  1. 为什么服务器端验证不在 Page_Load 之前发生?
  2. 为什么当我使用 Page.IsValid 时它工作正常?
  3. 您能否提供对解释此问题的文章的任何参考?(不是说 - 总是使用 Page.IsValid;而是说明使用 Page.IsValid
  4. 的强制性场景是什么

更新 1

参考 ASP.NET 验证器常见的误解

<块引用>

Page.IsValid 只有在运行 Page.Validate() 方法后才能访问,该方法在 Page_Load 之后隐式调用.如果您将所有逻辑保留在 Page_Load 事件处理程序中(强烈建议不要这样做!),请在检查 Page.IsValid 之前调用 Page.Validate().

注意:建议不要保留Page_Load中的所有逻辑.如果按钮单击事件发生某些事情,请将其移至按钮单击事件处理程序.如果下拉事件发生某些事情,请将其移至下拉选定项更改事件处理程序.

更新 2

看起来,我们需要在 button click 中添加 If(Page.IsValid) 同样,如果我们使用 Custom Validator服务器端验证.请参阅 CustomValidator 运行不佳.

注意:客户端验证问题出现在这里:是否使用 Page_IsValid 或 Page_ClientValidate() (用于客户端事件)

标记

<head runat="服务器"><title></title><script type="text/javascript">警报('哈哈');<身体><form id="form1" runat="server"><div><asp:ValidationSummary runat="server" ID="vsumAll" DisplayMode="BulletList" CssClass="validationsummary" ValidationGroup="ButtonClick"/><asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="valEmpName" runat="server" ControlToValidate="txtEmpName"EnableClientScript="false" ErrorMessage="RequiredFieldValidator" Text="*" Display="Dynamic"ValidationGroup="ButtonClick"></asp:RequiredFieldValidator><asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" ValidationGroup="ButtonClick"/>

</表单>

代码隐藏

protected void Button1_Click(object sender, EventArgs e){字符串值 = txtEmpName.Text;提交员工(值);}

参考资料:

  1. 我应该总是调用 Page.IsValid 吗?
  2. ASP.NET 验证控件 - 要点、提示和技巧
  3. CustomValidator 运行不佳

解决方案

验证发生在 Page_Load 之后,但在事件处理程序之前(请参阅 http://msdn.microsoft.com/en-us/library/ms178472(v=VS.100).aspx).

如果你的按钮没有引起验证,你必须手动触发 Page.Validate.

您不能询问 Page.IsValid,直到 (1) 您调用了 Page.Validate 或 (2) 导致验证的控件是/包含的源在回发中.

如果您需要在事件处理程序触发之前进行验证,您可以使用:

if (Page.IsPostback){Page.Validate(/*控制验证组名称可选*/);如果 (Page.IsValid){//做一些很酷的事情}}

您可能还想考虑重新设计,这样您就不需要这样做了.

在处理导致验证的控件的事件处理程序中,保证 Page.IsValid 可用.在所有其他情况下,重新请求验证通常更安全.在具有验证器的表单上处理提交的一种模型:

void btnSubmit_Click(object sender, EventArgs e){this.UpdateGUIWithSubmitRequest();如果 (Page.IsValid){this.ProcessSuccessfulSubmission();}别的{this.ProcessInvalidSubmission();}}

如果您使用的 CustomValidator 具有非常昂贵的验证步骤,您可以考虑将结果缓存在 HttpResponse.Cache 中,这样您就不必重新验证是否多次调用 Page.Validate.

void CustomValidator_ServerValidate(object source, ServerValidateEventArgs args){CustomValidator self = (CustomValidator)source;string validatorResultKey = self.ClientID;布尔?validatorResult = Context.Items[validatorResultKey] as bool?;if (validatorResult.HasValue){args.IsValid = validatorResult.Value;返回;}bool isValid = this.DoSomethingVeryTimeConsumingOrExpensive();Context.Items[validatorResultKey] = isValid;args.IsValid = isValid;}

这当然 100% 取决于您的架构,以及您是否能够假设在初始验证期间通过/失败的验证在同一页面生命周期的后续验证期间仍然通过/失败.

I have following code with a RequiredFieldValidator. The EnableClientScript property is set as "false" in the validation control. Also I have disabled script in browser.

I am NOT using Page.IsValid in the code behind. Still, when I submit without any value in textbox I will get error message.

From comments of @Dai, I came to know that this can be an issue, if there is any code in Page_Load that is executed in a postback. There will be no validation errors thrown.

(However, for button click handler, there is no need to check Page.IsValid)

if (Page.IsPostBack)
{
    string value = txtEmpName.Text;
    txtEmpName.Text = value + "Appended";
}

QUESTION

  1. Why does not the server side validation happen before Page_Load?
  2. Why does it work fine when I use Page.IsValid?
  3. Can you provide any reference to an article that explains this? (Not something that says - always use Page.IsValid; but something that says what are the mandatory scenarios to use Page.IsValid

UPDATE 1

Refer ASP.NET Validators Common Misconception

Page.IsValid is accessible only after running Page.Validate() method which is invoked implicitly somewhere after Page_Load. In case you keep all of your logic in a Page_Load event handler (which is highly discouraged!), call the Page.Validate() before checking the Page.IsValid.

Note: It is advised not to keep all the logic in Page_Load. If something is to happen on button click event, move it to button click event handler. If something is to happen on drop-down event, move it to drop-down selected item change event handler.

UPDATE 2

It seems like, we need to add If(Page.IsValid) in button click also if we are using a Custom Validator with server side validation. Refer CustomValidator not working well.

Note: Client side validation question is present here: Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)

MARKUP

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
    alert('haiii');
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:ValidationSummary runat="server" ID="vsumAll" DisplayMode="BulletList" CssClass="validationsummary" ValidationGroup="ButtonClick" />
    <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="valEmpName" runat="server" ControlToValidate="txtEmpName"
        EnableClientScript="false" ErrorMessage="RequiredFieldValidator" Text="*" Display="Dynamic"
        ValidationGroup="ButtonClick"></asp:RequiredFieldValidator>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" ValidationGroup="ButtonClick" />
</div>
</form>
</body>
</html>

CODE BEHIND

protected void Button1_Click(object sender, EventArgs e)
{
    string value = txtEmpName.Text;
    SubmitEmployee(value);
}

References:

  1. Should I always call Page.IsValid?
  2. ASP.NET Validation Controls – Important Points, Tips and Tricks
  3. CustomValidator not working well

解决方案

Validation occurs after Page_Load, but before event handlers (See http://msdn.microsoft.com/en-us/library/ms178472(v=VS.100).aspx).

If your button does not cause validation, you must manually fire Page.Validate.

You may not interrogate Page.IsValid until after (1) you have called Page.Validate or (2) a control that causes validation was the source of/included in a postback.

If you require validation to occur before event handlers fire, you may use:

if (Page.IsPostback) 
{
   Page.Validate( /*Control Validation Group Name Optional*/ );
   if (Page.IsValid)
   {
       //Do some cool stuff
   }
}

You may also want to consider redesigning so you aren't required to do so.

In an event handler that handles a control which causes validation, Page.IsValid is guaranteed to be available. In all other cases, it is generally safer to re-request validation. One model for handling submissions on a form that has validators:

void btnSubmit_Click(object sender, EventArgs e)
{
   this.UpdateGUIWithSubmitRequest();
   if (Page.IsValid)
   {
      this.ProcessSuccessfulSubmission();
   }
   else
   {
      this.ProcessInvalidSubmission();
   }
}

If you are using a CustomValidator that has a very expensive validation step, you may consider caching the result in the HttpResponse.Cache so you do not have to re-validate if multiple calls to Page.Validate occur.

void CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
   CustomValidator self = (CustomValidator)source;
   string validatorResultKey = self.ClientID;
   bool? validatorResult = Context.Items[validatorResultKey] as bool?;
   if (validatorResult.HasValue)
   {
      args.IsValid = validatorResult.Value;
      return;
   }

   bool isValid = this.DoSomethingVeryTimeConsumingOrExpensive();
   Context.Items[validatorResultKey] = isValid;
   args.IsValid = isValid;
}

This, of course, depends 100% on your architecture and whether or not you are able to assume that a passed/failed validation during initial validation still passes/fails during subsequent validations of the same Page Life Cycle.

这篇关于Page.IsValid 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆