I'm working with a legacy project in C# (.NET 2.0). In this project there are two validationgroups. One for custom login control and one for users to submit to a newsletter. The problem I ran into is that when a user submits to subscribe to a newsletter some custom code is triggered in the page_prerender() method which only should be triggered when a user tries to login.
I have been looking for a solution to recognize which of the two groups is used on postback so I can ignore the custom code when needed. My idea was to try and check which of the two validation groups is being used to validate. Unfortunately after spending a fruitless few hours on google I've not been able to find anything to let me know how to actually known which validationgroup is used when validating. Is there any way to find out?
<asp:Button ID="btn_newsletter"
runat="server"
Text="Verzend"
ValidationGroup="newsLetter"
meta:resourcekey="bnt_newsletter"
OnClick="handleNewsLetter"
CssClass="roundedButtonBig"
/>
<asp:Button ID="LoginButton"
runat="server"
CommandName="Login"
Text="Inloggen"
ValidationGroup="lgnUser"
meta:resourcekey="LoginButtonResource1"
CssClass="roundedButtonBig"
/>
The following code should only trigger when the LoginButton is pressed and it needs to be done on Pre_render(). Or alternatively pass the correct ValidationGroup (where now null is passed).
protected void Page_PreRender(object sender, EventArgs e)
{
//Register custom ValdiationErrorService added errors to JavaScript so they can be added into the popup.
ValidationErrorService.RegisterServerValidationMessageScript(Page, null);
}
to check which validation group is valid, call:
Page.Validate(“newLetter”);
then check
Page.IsValid;
this will return the value. Scott Gu has more on his blog
edit you are also wanting to know which button was clicked within the prerender event it sounds like as well. While you can't find that out from the parameters passed into the page prerender, you can rely on the button events occuring prior to the page_prerender event. within the aspx pages code behind, create a member variable. this variable will be used to denote if the prerender logic should be executed.
next, within the click events of the two buttons, set that local variable to denote if that button should fire the logic you want in the page_prerender event.
last, check your local variable within the page_prerender method, and encapsulate your logic within an if statement based upon your new member variable.
Happy Trails!
Related
I have an ASP.NET C# web form that uses jquery to validate user input before that input is handled by the server. When I say "validate", I mean that I check to ensure my user has given input in certain required fields before anything else happens. This check is wired to the "OnClientClick" event of an ASP.NET button control. If the client script finds missing input, it returns false. Otherwise, the button's OnClick event fires.
<asp:Button ID="submitBtn"
OnClientClick="if (!addBtnClick(event)) { return false; }"
UseSubmitBehavior="false"
runat="server" Text="Submit" OnClick="submitBtn_Click" />
The inputs to be checked consist of textboxes and drop down lists, both of which are coded in the page as server controls, and marked as required by a class value. I check the value of these inputs one at a time using the "each" function, and get the value of the input being checked with "$(this).val()".
$(cls).each(function () {
var val = $(this).val();
// do other stuff
});
My problem is that this is somehow causing an "Invalid postback or callback argument" error, and I know it's "$(this).val()" that's the culprit because if I comment out only that, passing in some generic value to my variable for example, my application runs fine.
I've tried registering my jquery code with RegisterClientScript, but that doesn't change anything. Has anyone seen this before?
EDIT: "$(this).val()" continues to throw this error even if the server-side isn't involved. I'm using this code to reset my form as well, clearing all input fields. After posting this it occurred to me that some of my textboxes have event listeners attached, so maybe this is where the error is coming from?
Turns out, no. Even with my event listeners commented out, I still get the error on the client side. I can use "$('input').val('')" with no problem, but this clears all the input fields and I need to be able to ignore certain ones.
Synopsis:
I have a login page has two bootstrap modals, one for registering a new account and one for logging into an existing account. Intermittently I'm seeing an issue where trying to log in results in the method for the registering submit button being fired instead of the method for the login button (the one clicked).
Details:
I'm going to describe some of the layout and post code where necessary. I'm trying to avoid posting a ton of code since I'm not exactly sure where the issue lies. This page is a childpage of the site.master, has multiple .css and .js files associated with the theme and the site functionality.
'signup-modal' modal includes a few input fields and then the submit button 'Button1', whose onclick parameter fires the server-side 'RegisterUser' method in the code behind file (C#).
'login-modal' modal includes inputs for username/password, a remember me checkbox, a login with facebook button and the submit button, whose onclick parameter fires the server-side 'ValidateUser' method in the code behind file (C#).
Each modal is surrounded by an UpdatePanel.
When a user has the login modal open and fills valid information then clicks the login button it will typically operate as expected, firing the 'ValidateUser' method, checking the information with the database and authenticating/redirecting the user to the content page. However, occasionally when clicking the login button the 'RegisterUser' method fires instead and returns an error I coded for when the DB tells it that the username entered already exists.
Unfortunately I can't seem to consistently recreate this error, but it does seem to be related to the authentication. I'm using FormsAuthentication to set authentication cookies for the user once they've been validated by the user database. I've noticed that when this error happens, if the cache is cleared, then you are able to login successfully.
What I don't understand is why anything in Session authentication should cause the wrong method to fire onclick. Especially since when it fires the button control it's associated with is hidden and should be inaccessible. The best I can figure is that somehow all onclick methods are being fired and because the 'RegisterUser' one is first in the html, that is the one being executed?
What I've Tried:
I had read a couple posts where people would see this type of behavior as a result of blank labels:
ASP.NET: Wrong event is fired when I click a LinkButton
I don't see anything like that in my code, however I did have a class="" call out in an ASP:Button control that was generating a warning about class="" not being a valid parameter. I tried removing that but didn't see any change in behavior.
I have included on both forms (in each modal) required field parameters, which I remove/add VIA javascript when the modal is hidden or shown. The reason I remove it is that an error is thrown if a required field is hidden due to the browser trying to find the control to validate and not seeing it. Since the 'RegisterUser' method fires without the browser trying to authenticate the associate fields I can surmise that the button is actually hidden (with the required parameters removed) and not just off screen or something.
I have tried without success to determine why this only happens intermittently. It doesn't seem to be due to the number of authenticated sessions under one username. I have logged into over 5 sessions on different computers/browsers without getting the error and had it happen on the first login attempt for a user.
Also, I can confirm that I've seen this error across Chrome, IE, Edge and Firefox, again intermittent on all.
I've double checked that the 'RegisterUser' method isn't being called anywhere else besides the onclick function of the register button.
I haven't been able to find any other posts similar to this, so I'm turning to you in desperation.
The Question:
So if you've made it through all that, here's the real question; What would cause the wrong OnClick method to fire? Am I correct in my educated guess that it has something to do with the Session authentication?
I would also appreciate some advice on where to take my troubleshooting from this point. I can post code snippets as necessary, I'm just not sure what would be relevant and given the volume of code I didn't want to just post it all.
Code Snippets:
The buttons:
Register Button:
<asp:Button ID="Button1" runat="server" onclick="RegisterUser" Text="Create Account" CssClass="btn btn w-lg btn-rounded btn-lg btn-custom waves-effect waves-light" />
Login Button:
<asp:Button ID="btnSubmit" runat="server" onclick="ValidateUser" Text="Sign In" CssClass="btn btn w-lg btn-rounded btn-lg btn-custom waves-effect waves-light" />
Outline of RegisterUser Method
protected void RegisterUser(object sender, EventArgs e)
{
/* Code that registers user with database if username doesn't exists */
}
Outline of ValidateUser Method
protected void ValidateUser(object sender, EventArgs e)
{
/* Code that validates user with the database and authenticates if valid. */
}
Please let me know if there is any more information that would be helpful to include and I'll update the question.
Thank you very much in advance.
UPDATE
I̶'̶v̶e̶ ̶f̶o̶u̶n̶d̶ ̶t̶h̶a̶t̶ ̶I̶'̶m̶ ̶a̶b̶l̶e̶ ̶t̶o̶ ̶r̶e̶p̶r̶o̶d̶u̶c̶e̶ ̶t̶h̶i̶s̶ ̶e̶r̶r̶o̶r̶ ̶1̶0̶0̶%̶ ̶w̶h̶e̶n̶ ̶r̶u̶n̶n̶i̶n̶g̶ ̶o̶n̶ ̶l̶o̶c̶a̶l̶h̶o̶s̶t̶ ̶a̶s̶ ̶o̶p̶p̶o̶s̶e̶d̶ ̶t̶o̶ ̶t̶h̶e̶ ̶d̶e̶v̶e̶l̶o̶p̶m̶e̶n̶t̶ ̶s̶e̶r̶v̶e̶r̶.̶
(Turns out this isn't the case)
Here's another odd behavior I seem to have stumbled upon. If I type out the user name and password, the RegisterUser method fires. However, if the username and password are filled by a password manager, the ValidateUser method is fired (Correct action).
Check your button declaration in your .aspx source.
If you have a 'runat=server' and onclick="RegisterUser", and you have an event handler in your code-behind, it will cause the event to be fired twice.
If so try to change this
<asp:Button ID="Button1" runat="server" onclick="RegisterUser"
Text="Create Account" CssClass="btn btn w-lg btn-rounded btn-lg btn-
custom waves-effect waves-light" />
To this
<asp:Button ID="Button1" runat="server" Text="Create Account"
CssClass="btn btn w-lg btn-rounded btn-lg btn-custom waves-effect
waves-light" />
Some others say that adding type="submit" has helped them out.
Another case might be that your event handler in the server side might be causing the event to be triggered twice.
For instance if you have:
Protected Sub RegisterUser_OnClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles RegisterUser_Click
'Do Something
End Sub
The Handles RegisterUser_Click might cause the event to be fired twice.
Nice explanation btw. Hope the best. Lets us know what was the issue. Best of luck.
I'm trying to use the onclickserver on ASP.net to do something when the user clicks on a button but when I click the button nothing happens.
I really can't see what I'm doing wrong.
Here is the button:
<button id="BttnLead" class="bttnBlck" runat="server" onserverclick="BtnLead_OnClick">Lead</button>
And here the event I'm trying to use:
protected void BtnLead_OnClick(object sender, EventArgs e){}
Thank you.
I would bet it has to do with failed validation somewhere on the page, as #kman pointed out in a comment above. Are you using any <asp:FieldValidator/> controls anywhere on the page? If so, and they're not being handled correctly, all you would need to do to cause this button's postback to be triggered is to add the CausesValidation="false" property to the <button> control. This would have the button avoid the validation code that is (if it's the issue, which I really think it is) inevitably failing and thus never reaching the handler method.
P.S. It should be noted that you do NOT have to use an ASP.NET control (i.e. <asp:Button>) and the pure HTML <button> control with the runat="server" property renders a server side control just the same. However, if you're in the ASP.NET world anyway and you have access to these controls, they do provide some benefit that is nice; but that's a different conversation.
I've put a CustomValidator on my form. I have not set its ControlToValidate property. In its ServerValidate event I've written the following:
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
args.IsValid = false;
}
I put a breakpoint to this method but it seems to never come to that point. But if I do this on another form it works like a charm.
The ValidationGroup property of both the button and the CustomValidator are the same
I tried deleting this property in both the button and the CustomValidator, still does not work.
It seems as there's something formwide. I just put a CustomValidator on the form and do not touch any of its properties other than just setting its ServerValidate event method.
EDIT: Here's the aspx part:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ErrorMessage="This is a test"
onservervalidate="CustomValidator1_ServerValidate"
ValidationGroup="PA"></asp:CustomValidator>
<asp:Button ID="btnPensionersOK" runat="server" Text="OK" Width="75px"
onclick="Button1_Click" ValidationGroup="PA" />
Try to force the validation in the button-click handler via Page.Validate:
protected void Button1_Click(Object sender, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
// servervalidate should have been called
}
}
Edit(from comments):
If you want the customvalidator to validate if nothing was entered/selected in your controls, you need to set ValidateEmptyText to true. You also might want to let the CustomValidator replace the RequiredFieldValidators.
I assume that the validator-order on the aspx decides whether or not a customvalidator's severvalidate is called if a previous Validator already has made Page.IsValid=false. Or ASP.NET is so smart that it assumes the SeverValidate to be costlier than a simple text-is-empty check.
I would also like to put some more help for those who will use CustomValidators and RequiredFieldValidators at the same time. One should take into account that Client side validation takes place first. And the server side validation will occur only after PostBack. I'm sure you got it but just in case this is not quite clear: It means first all the controls that are bound to certain client side working validators must be valid to let Postback to occur. After Page. IsValid is True server side stuff takes place and posts back any changes which includes server side validation messages.
So here are the ways one can make both CustomVCalidators and other built in validators to work at the same time.:
Set both groups of validators to work on Client side. In this case we must ensure that for the custom valitor(s) we spacify the script that will make validation on the client side. Without writing script and just filling in the ServerValidate method the validation will take place in the server.Even if EnableClientScript property is set to True.
Set both groups of validators to work on server side. To do so simply set EnableClientScript to False. But note that this will load the server.
In my asp.net web page, there are a few of buttons and checkboxs. They all can cause postback.
Can I detect which control is clicked? Because I will add code for if clicked a button then do something.
I saw that some examples are done with Jquery.
Can we just do it in C#?
Thanks.
Why are you not just using the click behavior of the button:
ASPX
<asp:Button id="Button1"
Text="Click here for greeting..."
OnClick="GreetingBtn_Click"
runat="server"/>
CS
void GreetingBtn_Click(Object sender,EventArgs e)
{
}
reference here
You could check Request.Form["_EVENTTARGET"] for the control that generated the postback
well if each of the buttons submit a key value to the post or get parameters, and theyre all different it should be pretty easy! :)
localhost/home.html?button=clicked&link=selected
the above is an example of a get parameter url, you can use jquery to get those, or if its a post you would have access to them in a similar way...the previous page would have to have been a form though.
You could eventually do it by checking Request.Form["_EVENTTARGET"] but that is highly unusual and certainly not necessary.
Whatever you need to do, you can do it in the Click event handler of the given control.
You can set a server hidden control specifying the action (checkbox/textbox/button clicked) using javascript & retrieve that server control in page load to check its action & add your code for that action