How does Page.IsValid work?

前端 未结 2 505
情歌与酒
情歌与酒 2020-12-02 22:24

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

相关标签:
2条回答
  • 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.

    0 讨论(0)
  • 2020-12-02 23:21

    Submit button should have same validation group as validator control has. For example

     <asp:Button Text=" Submit " runat="server" ID="btnSubmit" OnClick="btnSubmit_Click" ValidationGroup="vgCustomerValidation" />
    
    0 讨论(0)
提交回复
热议问题