Adding an error message to the check summary

I am doing something like below in a web forms application;

protected void button_transfer_search_Click(object sender, EventArgs e) { Page.Validate("val1"); if (!Page.IsValid && int.Parse(txtArrivalDateTrf.Text) + 5 < 10) { return; } 

also, I have the following code in my aspx file;

 <div class="search-engine-validation-summary"> <asp:ValidationSummary ValidationGroup="transfer" runat="server" ShowMessageBox="false" /> </div> 

My question is how to add an error message to the page before returning so that the check summary can capture and display it. I know that we can do this in mvc easily, but I did not understand how to do this in web forms. thanks!

+6
source share
1 answer

Whenever I find this situation, this is what I do:

 var val = new CustomValidator() { ErrorMessage = "This is my error message.", Display = ValidatorDisplay.None, IsValid = false, ValidationGroup = vGroup }; val.ServerValidate += (object source, ServerValidateEventArgs args) => { args.IsValid = false; }; Page.Validators.Add(val); 

And in my ASPX code, I have a ValidationSummary control with a ValidationGroup parameter with the same value as vGroup .

Then, after I have loaded as many CustomValidators (or any other types of validators) with codebehind as I want, I just call

 Page.Validate() if (Page.IsValid) { //... set your valid code here } 

Calling the Page.Validate() method calls the lambda-related method of all inserted code lock validators, and if any result returns false, the page is invalid and returns without executing code. Otherwise, the page returns a valid value and executes a valid code.

+9
source

Source: https://habr.com/ru/post/887442/


All Articles