I have created a button that displays an ASPX Pop-Up when clicked. But if I click the button, the page is getting reloaded for the first time, If I click second time then it display a pop-up.
protected void btn_Click(object sender, EventArgs e)
{
btn.OnClientClick=string.Format("javascript:openModalPopUpWindow(‘PopUp.aspx’,’rwPopUp’); return false;");
}
Note://the open ModalPopUpWindow code is defined at a master JS file
2
Answers
At the moment when the page loads your button has no client side click event attached to it. The code you posted is sever side and is only assigning the button a client side click event after it has been clicked and posted back the first time.
Either assign the OnClick for the button directly in the aspx file (not the .aspx.cs file) or move your btn.OnClientClick code to page_load of the aspx.cs file. This will make sure the button has a client side click assigned when it first renders.
You don’t show all of the markup for that button. However, if you don’t return false for the client side click event, then a full-page post-back will occur.
I also suggest using a good popup dialog library such as jQuery.UI.
So, assuming you have both jQuery, and jQuery.UI installed and available?
Then say we want to pop a dialog, have user confirm the dialog, and if yes, then we want the server-side button code to run. Of course, the standard is that if the JavaScript client side returns false, then the server-side code does not run.
So, say a typical delete prompt that requires a confirm:
Note how the button has both a client side click event, and a server side click event. As noted, if JavaScript returns true (ok to the dialog box), then the button click code will run. If we hit cancel, then the JavaScript returns false, and the server-side button code does not run.
Our code behind is thus:
And the result is thus this:
You can of course also trigger a popup from server-side code by using script injection into the page.
And when the user hits ok, then again, we will run the server-side delete code, and we do this from client-side JavaScript by "clicking" a hidden button (the same delete code button we had in the first example.
Hence, we now have this markup:
And code behind is now this:
And the result is quite much the same as the first example, but the page will have a post-back on the button click.
Hence again, it looks like this:
So, the above 2 examples should give you some ideas. In the first example, we had a button with both a client side click event, and a server-side event. As noted, if the client-side JavaScript returns true, or false, that determines if the server-side event for that button will run or not.
In the second example, we used 100% server-side button to trigger the popup, and used a hidden button that is clicked by the JavaScript to run a given code behind block when user hits "ok" as opposed to cancel.