CausesValidation not working with custom validators - c#

I have custom validators on the aspx page and user needs to see the error message in summary as soon as they tab out of the control.
To achieve this, I am calling Page_ClientValidate('') on onblur event of each control. One of the custom validator I have is:
function ValidateCustomerId(oSrc, args) {
var txtCustomerId = document.getElementById(txtCustomerId);
if (txtCustomerId != null) {
var customerId = txtCustomerId.value;
if (!isInteger(customerId)) {
document.getElementById("customerIdAsterik").style.display = 'inline';
args.IsValid = false;
}
else {
document.getElementById("customerIdAsterik").style.display = 'none';
}
}
}
If user enters invalid entry and clicks on Cancel button, server side event is not getting fired untill it is clicked twice. Cancel button already has CausesValidation=false. I think this behaviour is due to calling on Page_ClientValidate() on onblur event, otherwise it works fine.
Is there to skip the client validations when they click on cancel button or is there any approach I could take to achieve this.

Similar kind of issue is listed here:
http://weblogs.asp.net/gurusarkar/archive/2013/05/30/after-first-postback-why-i-have-to-click-the-button-twice-for-postback-to-occur.aspx
Not sure if that applies but the Validation is fired due to the onblur.
So I think setting that Page_Block=false in the button click might work.

Related

Windows Form tabpage event

I have a windows form application , In which i created two tab pages. In one of the tab page i have a button to send email notification.
In the tabpage leave event i have some code to perform some other actions.
When i click on this button to send email. First it fires tabpage leave event , as ithe button contains button1.enabled=false; in the first line as below,
private void btnTestEmail_Click(object sender, EventArgs e)
{
btnTestEmail.Enabled = false;
bool sent = Support.SendEmail("Test Email", "This is a test email, Please ignore.", null);
--
}
But when i remove btnTestEmail.Enabled = false; code it is not firing tabpage leave event.
What could be the reason that it fires the leave event of tab page. As it is vbery strange behaviour. As i dont want to fire any event of tab page .
Regards
Changing btnTestEmail.Enabled to false will change the ActiveControl, which fires the Leave event.
According to MSDN:
When you change the focus by using the keyboard (TAB, SHIFT+TAB, and
so on), by calling the Select or SelectNextControl methods, or by
setting the ContainerControl.ActiveControl property to the current
form, focus events occur in the following order:
Enter
GotFocus
Leave
Validating
Validated
LostFocus
What you can do:
What I would do to eliminate this behavior is unsubscribing the Leave event and re-subscribing it after setting the Enabled property to false.
Like this:
this.tabPage1.Leave -= new System.EventHandler(this.tabPage1_Leave);
btnTestEmail.Enabled = false;
this.tabPage1.Leave += new System.EventHandler(this.tabPage1_Leave);
The Problem is, that the Leave event fires if the control isnt the active control. If you click the Button the TabPage changes from active to inactive because the Button is active control now.

Instantly disable Button on click

I'd like to instantly disable a Button after clicking it, so a User can't click it twice in short succession and fire the OnClick_Event twice in a row. btn.Enabled = false doesn't seem to do the trick instantly. Is there any other way to accomplish this?
Thanks,
Dennis
What you are doing is disabling it after a post back therefore your button will be disabled in the page that's rendered when the browser receives the response.
Do it on the client-side with JavaScript instead:
var button = document.getElementById('yourButton');
button.disabled = true;
If you're facing issues with posting back to the server, check out this article: How to disable an ASP.NET button when clicked.
function disable()
{
var button = document.getElementById('<%= Button1.ClientID %>');
button.disabled = true;
}
<asp:Button ID="Button1" OnClientClick="disable();">
you can achieve this via javascript
function Disable(btn)
{
btn.disabled = true;
}
and add this to your button OnClientClick="javascript:return Disable(this);"
You can handled it simply by this code.Suppose, here is a button named btnAdd.When you click this button it will be disable due to execute it's corresponding code.I mean due to post back it will be disabled.
if (!IsPostBack)
{
btnAdd.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(btnAdd).ToString());
}
Write the btn.Enabled= false at the end of all the functionality in the Onclick Event of the Button. It will do the Required action.
Disabling the button has raised on problem. You won't get the server side event fired. So better seek the alternative by hiding the button (and yes displaying some friendly error message 'working', 'processing' etc.). The work out on how to disable asp.net button on postback would help. Thanks.
YourButton.Enabled = false;
if(!YourButton.Enabled)
{
\\Your Code Here
YourButton.Enabled = true;
}
Hope this helps ;)

asp.net stop button event running on Refresh

I have a button that has click event in my C#. This works great. However afetr pressing F5 to refresh the page I noticed the button event is fired. This occurs every time I click F5. I've added if(page.IsPostBack) and the method still runs.
Is there any way to stop this method from firing when the F5 Refresh button is clicked?
Thanks!
http://pastebin.com/9ycNraaT
try to use Response.Redirect("Your page ") after the your add/update code. it isn't good practice, but it will help you.
if(!page.IsPostBack)
NOT if(page.IsPostBack)
If you have a page that needs to be run once, you should implement logic in your code that prevents the same method from running multiple times. In pseudo-code:
if (canExecuteMethod()) {
executeMethod();
} else {
displayMessageThatMethodCannotBeExecuted();
}
For example, you can check a Session variable with canExecuteMethod(), which returns false when it is not present and is set in executeMethod():
function canExecuteMethod() {
return Session["methodIsExecuting"] == null
|| Session["methodIsExecuting"] == false;
}
function executeMethod() {
Session["methodIsExecuting"] = true;
// ...
}
Of course the use of a Session variable has it limits, so you might want to consider using a database or AppSettings variable instead.
No way. If once you click button (and post data) after refresh the same data will be sended.

ASP.NET - How to track event from previous postback?

I have a requirement to check for a certain condition on postback before redirecting (Response.Redirect) to another page.
Note... I cannot use JavaScript to detect whether or not to confirm (this is also a requirement) :s
Pseudo:
protected void lbtnRedirect_OnClick(object sender, EventArgs e)
{
if (showConfirm)
{
// Set flag for client side
this.ShowConfirm = true;
// Track this event for next postback.
}
else
{
Response.Redirect("somepage.aspx");
}
}
If the showConfrim flag == true, then the client will be show a modal dialog box asking them if they are sure they want to redirect. If the user clicks on "Yes", then the page posts back and the desired effect is that the lbtnRedirect_OnClick event is fired. How would I about tracking the lbtnRedirect event?
Edit:
I have no problem tracking the flag to show the modal (yes JS must be used to show the modal... somethings you just cannot get rid of :)). I should have been more clear.
It is when the user clicks "Yes" to continue the redirect. The page will postback again but needs to know which event to go through.
i.e. Suppose there are 3 onclick events, 1) lbtnRedirect1_Onclick 2) lbtnRedirect2_OnClick 3) lbtnRedirect3_OnClick... each of which does the confirm check.
Each onclick event does the check. So when the user clicks on "Yes" on the modal, how does the page know which event to drop back into?
You can use ViewState if you're in WebForms.
Implement a ShowConfirm property encapsulating ViewState["ShowConfirm"].
In the first postback you'll set ShowConfirm 'true', and this will activate that modal during the render (if ShowConfirm is true, that's setting as visible 'true' some control).
In the next postback, you'll set ShowConfirm 'false' because is 'true', and finally you'll do the whole redirect!
You can use an ajax call from javascript to set the required values.
Since the postback will happen before even the execution reaches to your button click event we need a workaround here, And if you don't need JS as your requirement, so take a look at
Implementing Client Callbacks Programmatically without Postbacks in ASP.NET
This is much like a wrapper for XMLHttp Ajax call IMHO.
You cannot easily create a model form, without javascipt.
One suggestion I would make is to have panels in your page.
Panel one is visible.
On submit one; panel one hides and panel two is visible asking for a confirmation.
On panel two is a confirm button, clicking this button your redirection is performed.

ASP .NET Button event handlers do not fire on the first click, but on the second click after a PostBack

Background: I am customizing an existing ASP .NET / C# application. It has it's own little "framework" and conventions for developers to follow when extending/customizing its functionality. I am currently extending some of it's administrative functionality, to which the framework provides a contract to enforce implementation of the GetAdministrationInterface() method, which returns System.Web.UI.Control. This method is called during the Page_Load() method of the page hosting the GUI interface.
Problem: I have three buttons in my GUI, each of which have been assigned an Event Handler. My administration GUI loads up perfectly fine, but clicking any of the buttons doesn't do what I expect them to do. However, when I click them a second time, the buttons work.
I placed breakpoints at the beginning of each event handler method and stepped through my code. On the first click, none of the event handlers were triggered. On the second click, they fired.
Any ideas?
Example of Button Definition (within GetAdministrationInterface)
public override Control GetAdministrationInterface()
{
// more code...
Button btn = new Button();
btn.Text = "Click Me!";
btn.Click += new EventHandler(Btn_Click);
// more code...
}
Example of Event Handler Method Definition
void Btn_Click(object sender, EventArgs e)
{
// Do Something
}
Page_Load Method that calls GetAdministrationInterface
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsAsync)
{
List<AdministrationInterface> interfaces = <DATABASE CALL>;
foreach(AdministrationInteface ai in interfaces)
{
placeholderDiv.Controls.Add(ai.GetAdministrationInterface());
}
}
}
Good grief! I knew it was going to be something this stupid. Purely my fault of course and my lack of knowledge in ASP .NET.
After doing a multitude of Google searches and eventually being blocked by Google on suspicion of being a bot running automated scripts, I managed to squeeze in one last search in and stumbled across this article. Already at the point of giving up, I tried my best to read the article without skipping 10 lines at a time or looking for pretty pictures. In the section titled Assigning IDs to Dynamically Created Controls, I read these magical and most joyful words:
If you view the source HTML before you click the not-working button and after you have clicked it, you will notice a small difference. The buttons have different HTML IDs before and after the post-back. I got ctl04 and ctl05 before the post-back and ctl02 and ctl03 after the post-back.
ASP.NET button recognizes events by checking for a value for its ID in the Request.Form collection. (In truth it happens differently and controls do not check Request.Form collection by themselves. Page passes post data to controls by their IDs and to controls that are registered to be notified about post data). ASP.NET does not fire the Click event, because the button's ID has changed between the post-backs. The button you have clicked and the button you see after are different buttons for ASP.NET.
Sure enough, when I viewed the HTML the first time, my button had the ID ctl04$ctl36. After clicking the button, my button had the ID ctl04$ctl33.
So there you have it! All I had to do was set the ID on the buttons and presto! My event handlers are now being called!
Sample Solution:
public override Control GetAdministrationInterface()
{
// more code...
Button btn = new Button();
btn.Text = "Click Me!";
// !!THE BANE OF MY EXISTENCE!!
btn.ID = "The_Bane_of_My_Existence";
// !!THE BANE OF MY EXISTENCE!!
btn.Click += new EventHandler(Btn_Click);
// more code...
}
What a great way to spend two days...
I had the same problem, but the accepted answer here was not causing it. I had a text box and a search button, and clicking the button the first time didn't perform the search. The event handler of the button wasn't being hit. But clicking the button a second time did trigger the event on the server. Here is why:
If you have an <asp:Textbox> with its AutoPostBack set to true, after typing in the text box and then moving to click a button, the text box causes a post-back immediately the moment it loses focus. So the click even of the button doesn't count (the page is already posted-back as a result of the text box's event). That's why when you click the button a second time, it works because the text box is not involved in the second post-back.
Set the AutoPostBackproperty of the <asp:Textbox> to false to fix this issue.
A quick fix is to set an ID to the ASCX control your are loading on a page. For example, if your code is like this:
UserControl SpecsControl = (UserControl)Page.LoadControl("../name.ascx");
SpecsContainer.Controls.Add(SpecsControl);
then you need to add a line (before Controls.Add):
SpecsControl.ID = "Aribtrary_Name";
Then your handler method is fired at the first click.
I was facing the same problem. My button froze after my first click. For me this annoying problem got solved when I disabled the button's EnableViewState attribute.
For me it was the UpdatePanel , my Button and my TextBox were both inside an UpdatePanel , so when I post-back , it caused some weird behavior . It took it outside of the UpdatePanel and that fixed it .
Even i had the same problem. the cause was "localhost:1656/secure/login.aspx?ReturnUrl=%2f".
if the request contain %2f as query string, the first post will not be succeeded even though "%2f" is representing "/".
one way to avoid this by having a condition check in pageload
protected void Page_Load(object sender, EventArgs e)
{
string queryString = Request.QueryString.ToString();
if(queryString == "ReturnUrl=%2f")
{
Response.Redirect("/secure/login.aspx");
}
}
Whilst its hard to know exactly without seeing the full Page_load method it does smell a little bit like the event handlers are not hooking up until the page is reloaded.
eg:
if (IsPostBack) {
// Add handlers here ...
}
I had same problem. And I searched on internet i didnt find a solution. After that i found sample code and I used it. It worked for me. Web site link is below:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/calling-an-Asp-Net-C-Sharp-method-web-method-using-javascript/

Categories