I have an asp.net page with multiple validation summaries setup with ShowMessageBox="True" and several validators. I have run into a situation where when validation fails the validation summary displays correctly but then the next click that would normally trigger a postback of the page does not trigger a postback. So the steps look like this:
Click button that triggers validation.
Validation fails and a messagebox with the failure message is displayed.
Click a different button which does not validate but should trigger a postback nothing happens
Click same button as step 3 again postback happens as expected.
What could cause this behavior?
EDIT: The validation was being done in the following manner. In the asp page:
<asp:Button runat="server" id="btn" onClientClick="return DoValidation();" />
In the javascript:
function DoValidation() {
if (!Page_ClientValidate('group1'))
return false;
if (!Page_ClientValidate('group2'))
return false;
return true;
}
After working on this and making careful use of the debugger I finally found out that when you do validation the way described in the edit to the question a boolean is set on failure that blocks the next PostBack of the page from going through. I believe this is done when validation is being done automatically instead of explicitly as I'm doing here. Changing the javascript described above to look like this:
function DoValidation() {
if (!Page_ClientValidate('group1')) {
Page_BlockSubmit = false;
return false;
}
if (!Page_ClientValidate('group2')) {
Page_BlockSubmit = false;
return false;
}
return true;
}
Causes the problem to go away. Hopefully this will help the next person who makes the same mistake I did.
Related
I'm new to web programming with .NET.
I am developing a web page with webforms, and I want at a certain moment to programmatically show a modal window, for the user to accept or cancel, according to a question. Exactly what does the "confirm" function of JavaScript.
I tried to get it calling a JavaScript function:
Page.ClientScript.RegisterStartupScript (this.GetType (), "CallMyFunction", "MyFunction()", true);
But I need to do it without reloading the page, and I also need to control if the user has accepted or canceled and I do not know how to do it.
I've also tried getting it using the ModExPopupExtender control from DevExpress.
Can someone tell me a simple way to get what I want?
I can not understand how something so usual in web programming, and that PHP + javascript would not pose any problem can be so complicated.
All start in a one-button event on the code behind:
protected void btn1_Click(object sender, EventArgs e)
{
//I make a series of checks
//If certain conditions I want to show the confirm
//According to the user has chosen ok or cancel will perform a certain action
}
Onclientclick does not help me because before launching the "confirm" I have to do some checks on the server side.
Thank you very much.
You can use OnClientClick which is a property on most web controls.
I like to just bring up a simple confirm() dialog which executes the server code if the user clicks OK and does nothing if the user cancels the action:
<asp:Button runat="server" ID="btnSave" Click="btnSave_Click" Text="Save"
OnClientClick="return confirm('Are you sure you want to do this thing?');" />
You can do other things with it as well, but the key thing to remember is that anything you do in OnClientClick will happen before the page gets posted back to the server.
This is also perfectly valid:
<asp:Button runat="server" ID="btnSave"
OnClientClick="showModalConfirm('some message goes here');" ... />
<script>
function showModalConfirm(msg)
{
$(".modal .message").innerHtml(msg);
$(".modal").Show();
}
</script>
You can set the action that OnClientClick should perform in your codebehind in exactly the same way:
protected void Page_Load(object sender, EventArgs e)
{
btnSave.OnClientClick = "return confirm('Are you sure you want to do this thing?');";
}
You can use below code in c# to call javascript function. Below code will execute afterpostback() javascript function:
ClientScript.RegisterStartupScript(GetType(), Javascript, "javascript:afterpostback();", true);
And you can write code in javascript function to display any div or popup:
<script language="javascript" type="text/javascript">
function afterpostback() {
//Here you can write javascript to display div/modal
}
</script>
One way I've handled this previously was to have 2 buttons on the page. The first would be initially visible and labeled "Submit". The second would be initially hidden and labeled "Confirm". The "Submit" button would postback upon click and perform your server side checks/validation. If those checks failed, an appropriate error message would be displayed. If those checks passed, an appropriate "Please confirm your submission"-type message would be displayed, the "Submit" button would become hidden, and the second "Confirm" button would become visible. When that Confirm button was clicked, it would postback again and fully submit.
EDIT: I forgot to mention, there's a bit more to this that occurred to me after I initially posted. You'll have to protect the fields from being edited in the event the server-side verification is successful as you obviously don't want the user changing values and then clicking the Confirm button. That means disabling all the input controls - which could be a pain if you have a lot. You also have to give them a way to (intentionally) Edit in case the server side verification passes, you display the Confirmation, and they change their minds - so basically you'd need a third "Cancel/Edit"-type button that would put the form back in edit mode and show your initial Submit button.
I have got a checkbox and want to display the confirmation message when it is clicked
I added the event binding in Code Behind file as below.
chkSMTLock.Attributes.Add("onclick", "return ConfirmSMTLock();");
The following is my HTML code for chkSMTLock
<asp:CheckBox ID="chkSMTLock" runat="server" AutoPostBack="true" OnCheckedChanged="chkSMTLock_CheckedChanged" Text="SMT Lock" />
Here is my javascript:
function ConfirmSMTLock() {
var r = confirm('Are you sure that you want to SMT lock/unlock this account?');
console.log(r);
return r;
}
When I run it, I can see the confirmation values (true/ false) in the browser console logs, but, it's not calling any server side code.
My server side code is very simple with logging...
protected void chkSMTLock_CheckedChanged(object sender, EventArgs e)
{
Utils.Debug("chkSMTLock_CheckedChanged");
}
When I remove javascript event binding for the checkbox, it executes the ServerSide event successfully. But When I put it back, it stops working.
How can I use the confirmation message box to control it?
Your validation is too far down the chain. As you've got AutoPostBack=true, you're basically submitting a form when clicking the checkbox, your validation wants to be at the form level.
Form.Attributes.Add("onclick", "return ConfirmSMTLock();");
And in ConfirmSMTLock() check the status of the checkbox to see if you need to fire the confirm dialogue. That's the simplest way I can think of.
On a side note: if you do this:
chkSMTLock.Attributes.Add("onclick", "return false;");
The checkbox becomes untickable
I have found out an answer. Since AutoPostBack = true, it will automatically send a post back to the server. So, first you need to delete that attribute from the html code.
<asp:CheckBox ID="chkSMTLock" runat="server" OnCheckedChanged="chkSMTLock_CheckedChanged" Text="SMT Lock" />
Then implement the PostBack behaviour by using the __doPostBack function of ASP.Net.
function ConfirmSMTLock() {
var r = confirm('Are you sure that you want to SMT lock/unlock this account?');
if (r == true)
{
__doPostBack("chkSMTLock", '');
return true;
}
return false;
}
Open Sasame!!!
I have a page with a textbox control, a Custom Validator, a button to save entered data and code to handle the custom validation.
I set up a simple code test just to see how the Custom Validators work.
I hope to add more validations that check multiple controls later. The same thing happens if I do add the ControlToValidate attribute for the textbox control.
(I don't think I need a "ControlToValidate" attribute for this. I plan to validate multiple controls later. I can't put all the controls I am validating in that attribute.)
When I run my app, the save takes place and the validation is happeing - the message appears. I don't understand why the save isn't stopped when I enter "3" in the textbox I am checking. If the validation is happening, and if the IsValid = false, why is the save taking place?
Here is the Custom Validator:
<asp:CustomValidator ID="VisitSaveCustomValidator" runat="server" OnServerValidate="VisitSaveCustomValidator_ServerValidate" ValidationGroup="SaveVisit_val"></asp:CustomValidator>
Here is the button:
<asp:Button ID="SaveVisit_btn" runat="server" Visible="false" Text="- Save Visit -" ValidationGroup="SaveVisit_val" OnClick="SaveVisit_btn_Click" />
Here is the code for the Custom Validator:
protected void VisitSaveCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
if (VisitNumber_tbx.Text == "3")
{
args.IsValid = false;
VisitSaveCustomValidator.ErrorMessage = "The Visit Number cannot be 3.";
}
else
{
args.IsValid = true;
}
Please let me know if I need to add more code or more information.
I thought this would be pretty straight-forward. I followed an example in a book and some online. I understand that the page is going back to the server to be validated. But, shouldn't the save be stopped since the IsValid = false?
It seems like the save is happening first, then the validation code executes, which causes the message to appear.
Thanks.
I believe you may have to manually call the validate method.
VisitSaveCustomValidator.Validate();
Then check to see if it was valid.
VisitSaveCustomValidator.IsValid();
This can be put in the button click event.
This is my LinkButton:
<asp:LinkButton OnClientClick="Page_ClientValidate('validPanel1'); if(Page_IsValid==false) { console.log('error'); return false; }" ID="linkPanel1" ValidationGroup="validPanel1">Check</asp:LinkButton>
if the page is not valid, ok, I get the summary. If it's valid, it do a postback to the server (also if I have return false).
I don't want this. I want a sort of "void" function (later, I catch the event through a jquery handler).
How can I do it?
Link button is designed to postback every time, since it is server side control.
If you want to avoid its postback, you will have to handle all the code clientside, by writting javascript function.
Try Following:
LinkButton1.Attributes.Add("onclick", "JSFunction();return false;")
here JSFunction() is javascript function.
This will not postback.
i have a validationSummary in my page. i want to call a javascript function after the validationSummary is filled. how can i achieve this?
i think i should add an attribute in the code behind, but i can't figure out what is the attribute's key.
any help?
You will want to call the javascript function Page_ClientValidate() to initiate the ASP.NET validation wired to your page controls. Once this is called, the Page_IsValid boolean value will be properly set.
Here is an example of how I am using it. If ASP.NET validation is successful, I disable the button, otherwise the button remains enabled and the validation summary is displayed to the user. The OnClientClick is from a ASP:Button control.
OnClientClick="javascript:Page_ClientValidate(); if (Page_IsValid==true) { this.disabled=true; }"
I don't think that's possible. It is, however, possible to intercept validation by setting OnClientClick on the controls that do postbacks. Then you can check the global JavaScript variable Page_IsValid for the validation result.
One thing to keep in mind is that, when there are no validators on a page, Page_IsValid will be undefined.
I started to implement the solution by #EverettEvola but also where the validation logic was being called multiple times and displaying multiple ValidationSummary popups. My solution was as follows:
On the button (in my case the button was a submit button)
OnClientClick="return CustomValidationOnClick()"
And the CustomValidationOnClick()
function CustomValidationOnClick(source, args) {
//Manually kickoff page validation
//This call will display the Validation summary popup if page is invalid
Page_ClientValidate();
//Page_IsValid set by the result of the Page_ClientValidate() call
if (Page_IsValid == true) {
this.disabled=true;
return true; //if Submit button return true to continue form submit
}
else {
//do whatever here
return false; //if Submit button return false to cancel form submit
}
}