Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

asp.net - How does Page.IsValid work?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...