Invoke OnClientClick of button in code behind - c#

I have an button in my aspx web page, which should be 'clicked' in my code behind c# code. The OnClientClick method then call a JS confirm dialog box and so the btn_Click function only get executed when user click 'OK'...
This is my code so far:
Variante 1
aspx:
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_Click" />
aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
// set OnClientClick
btnConfirm.OnClientClick = "confirm('Save in DB?');";
// invoke method
Type t = typeof(System.Web.UI.WebControls.Button);
object[] p = new object[1];
p[0] = EventArgs.Empty;
MethodInfo m = t.GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance);
m.Invoke(btnConfirm, p);
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
//save something in database
}
Got code samples by: http://forums.asp.net/t/1046550.aspx?How+do+you+raise+a+button+click+event+from+outside+the+button+
I want to call the OnClientClick method, but when I replace 'OnClick' with 'OnClientClick' this error appear:
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Edit:
Variante 2:
I tried to rewrite my program like this:
aspx:
<script language="javascript">
function invokeButtonClick() {
document.getElementById("btnConfirm").click();
}
function Validate() {
return confirm('Save in db?');
}
</script>
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_Click" OnClientClick="return Validate();" />
aspx:cs:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(), "InvokeButton", "invokeButtonClick();", true);
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
// save something in database
}
But then the page postback before my btnConfirm_Click function get called...
Thanks,
Michael

If OnClientClick has a return value of true then the codebehind OnClick event will fire. If OnClientClick is returned false then it won't.
If OnClientClick doesn't return anything the codebehind event will fire regardless. So you want..
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_Click" />
<script language="javascript">
function Validate() {
return confirm('Save in db?');
}
</script>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
// set OnClientClick
btnConfirm.OnClientClick = "return Validate();";
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
//save something in database
}
UPDATE:
This post just came to my attention, don't know why I didn't include it in my original post but you can use 'OnClientClick' in the aspx tag:
<asp:Button runat="server" ID="btnConfirm" OnClientClick="return Validate();" Text="Confirm" OnClick="btnConfirm_Click" />
<script language="javascript">
function Validate() {
return confirm('Save in db?');
}
</script>

You need to Add both the events on the button click. OnClientClick handles the Client side script code and OnClick handles the server side event calling.
So add both events and there handlers. The NullReferenceException you are getting because of that.
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_Click" OnClientClick="return Validate();" />
and in your javascript code can be
function Validate(){
if (valied())
return true;
return false;
}

100% code behind confirmation! Sometiems its so annyoing to Code behind or Server side confirmation in asp.net when you want to Delete or Update something, I got its solution after a long search as below:
<asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="return confirm('Are you sure to BLOCK this customer ?')" OnClick="btnSave_Click" />
Now whenever you will click this button it 'll ask to confirm, if you 'll select "NO" page will not post and if you select "Yes" then page will post and your button click event will be fire... like below
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
}
// Before coming here,,,there will be confirmation
protected void btnSave_Click(object sender, EventArgs e)
{
GetCustomerInfo();
}

Related

Javascript function not reaching other function?

So the code I have is:
PrintPage.aspx
<asp:Button ID="ViewAuctionsButton" OnClientClick="checkValidated();" Text="Visa" CssClass="" runat="server" />
<script type="text/javascript">
function checkValidated() {
if (document.getElementById('remember').checked)
{
ViewAuctionsButton_Click;
}
else
{
ViewAuctionsButtonChecked_Click;
}
}
</script>
PrintPage.aspx.cs
protected void ViewAuctionsButton_Click(object sender, EventArgs e)
{
*do stuff*
}
protected void ViewAuctionsButtonChecked_Click(object sender, EventArgs e)
{
*do stuff*
}
I hope you are seeing what I am trying to do here. "remember" is a checkbox but that's not really important because I know for a fact that when I click the button it will run the if / else code in checkValidated. (I tried it with alert("") boxes.).
Now I have no idea how to make this run beucase it doesn't seem to react to the "ViewAuctionsButtonChecked_Click;".
But if I instead change the code to following:
<asp:Button ID="ViewAuctionsButton" OnClick="ViewAuctionsButtonChecked_Click;" Text="Visa" CssClass="" runat="server" />
Then it will run. But then I am missing the part about the checkbox being checked or not. Any ideas on how I can fix this?
Thanks in advance.
You should make the "remember" checkbox a server-side control, ie:
<asp:CheckBox ID="RememberCheckBox" ... />
That way you can use OnClick="ViewAuctionsButton_Click;", and get the checkbox's value inside that method:
protected void ViewAuctionsButton_Click(object sender, EventArgs e)
{
if (RememberCheckBox.Checked)
// do stuff
else
// do stuff
}

cancel server side submit funcion in asp.net with javascript

I also made this question before but the problems remains here:
I have this code:
<asp:Button ID="CrearCuenta" UseSubmitBehavior="false" OnClientClick="return validate()" runat="server" Text="Ready" />
The javascript code:
function validate()
{
return false;
}
But in case that it return true, how do i execute de server side onclick function?? Thats what i cannot figure out.
I know that similars question have been posted before, but none answer the question above.
I hope, here is what you need:
<asp:Button ID="CrearCuenta" UseSubmitBehavior="false"
OnClientClick="return validate()" OnClick="CrearCuenta_Click"
runat="server" Text="Ready" />
Javascript:
function validate()
{
if()
return false; //if validation fails
else
return true;
}
Server Side:
protected void CrearCuenta_Click(object sender, EventArgs e)
{
//Put server side processing here
}
Have you added the server side event handler?
In your page code:
<asp:Button ID="CrearCuenta" OnClick="btn_Click"....
In your code-behind:
protected void btn_Click(object sender, EventArgs e)
{
....
}
check this code
document.getElementById('YourFrom').onsubmit = function() {
return false;
}

OnClick and OnClientClick

I have an image button on a pop up page which is opened by another page
<asp:ImageButton
ID="Button_kalem_islemikaydet"
runat="server"
CausesValidation="False"
ImageUrl="~/images/butonlar/buyuk/Kaydet.jpg"
meta:resourcekey="Button_kalem_islemikaydetResource1"
OnClick="Button_ust_islemikaydet_Click"
OnClientClick="f2()"
Width="100" />
f2() is
<script type="text/javascript">
function f2() {
opener.document.getElementById("TextBox1").value = "hello world";
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.location.href = window.opener.location.href;
}
</script>
And Button_ust_islemikaydet_Click is another method implemented in aspx.cs file and it updates the database tables which are shown in the parent page in a GridView.
What I am trying to do is to doPostBack I mean refresh the opener(parent) page.And with these above codes refresh is working.However, parent page still shows the same data before the refresh.And the reason is that OnClientClick works before OnClick method
So my question is that is there any way I can run the method on OnClick and finish it and then run the OnClientClick method?
<form id="aspnetForm" runat="server">
<asp:Button Text="Click Me" ID="ClickMeButton" OnClick="ClickMeButton_OnClick" runat="server" />
<asp:HiddenField runat="server" ID="UpdateOpenerHiddenField" Value="false" />
<script type="text/javascript">
//1st approach
var updateOpenerField = window.document.getElementById("<%= UpdateOpenerHiddenField.ClientID %>");
if (updateOpenerField.value === "true") {
f2();
updateOpenerField.value = "false";
}
// for the 2nd approach just do nothing
function f2() {
alert("Hello, opener!");
}
</script>
</form>
protected void ClickMeButton_OnClick(object sender, EventArgs e)
{
//1st approach
UpdateOpenerHiddenField.Value = "true";
// 2nd approach
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2();", true);
}
No, you can't run server side code (OnClick event handler) before client side. OnCLientClick event was added to perform some validation before post back. There is only one way to do it - update the f2 method and post data on server via ajax
You can put your javascript inside a PlaceHolder tag which you make visible in your server-side OnClick handler.
aspx code:
<asp:PlaceHolder id="refreshScript" visible="false" runat="server">
window.opener.location.href = window.opener.location.href;
window.close();
</asp:PlaceHolder
cs code:
protected void button_Click(Object sender, EventArgs e) {
// do whatever
refreshScript.Visible = true;
}

OnClick event not firing on ModalDialog

I have a Modal Dialog:
function ShowPopup()
{
window.showModalDialog('dialog.aspx', null, 'status:no;dialogWidth:950px;dialogHeight:150 px');
}
Then its called in the code behind
Page.ClientScript.RegisterStartupScript(this.GetType(), "popUpScript", "ShowPopup();", true);
The dialog.aspx has two buttons:
<asp:Button id="btn1" runat="server" Text="Button 1" OnClick="btn1_Click"></asp:Button>
<asp:Button id="btn2" runat="server" Text="Button 2" OnClick="btn2_Click"></asp:Button>
However, the Click events in the code behind are never getting fired.
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn1_Click(object sender, System.EventArgs e)
{
Response.Redirect(url)
}
protected void btn2_Click(object sender, System.EventArgs e)
{
Response.Redirect(url);
}
}
I recall seeing this problem before and I think it is related to caching. Try adding this to your dialog.aspx page_load method when !IsPostBack
Response.AddHeader("Pragma", "no-cache")
To stop the browser caching the page and reusing it
Are you receiving any hidden JavaScript errors preventing the POST?

Problems with asp:Button OnClick event

Here is my button
<asp:Button ID="myButton" Text="Click Me" OnClick="doSomething(10)" runat="server" />
Here is the server function
public void doSomething(int num)
{
int someOtherNum = 10 + num;
}
When I try to compile the code I get the error "Method Name Expected" for the line:
<asp:Button ID="myButton" Text="Click Me" OnClick="doSomething(10)" runat="server" />
What am I doing wrong? Am I not allowed to pass values to the server from an OnClick event?
There are two problems here. First, the onclick event has a specific signature. It is
MethodName(object sender, EventArgs e);
Second, in the markup, you need to pass the Method name only with no parentheses or params.
<asp:Button ID="myButton" Text="Click Me" OnClick="doSomething" runat="server" />
Then change your codebehind as follows:
public void doSomething(object sender, EventArgs e)
{
....
}
The passing of parameters can done on a client side click event handler, in this case OnClientClick, but not on the server side handler.
There is simpler solution. You could use ASP button OnCommand event.
More about here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.oncommand.aspx
OnClick of the Button is an Event Handler. To hook a function to an eventHandler you need to obey the Contract that was defined by the EventHandler, as mentioned by Jose. OnClick is bound to a function of the format void doSomething(object sender, EventArgs e). So your function should be of the same format.
I am unsure why would want to pass a parameter to the Event Handler. If you want to take some manuplation you need to do that using some other control.
<asp:TextBox ID="txtNumber" runat="server" /><asp:Button ID="myButton" Text="Click Me" OnClick="doSomething" runat="server" />
And in the Code
public void doSomething(object sender, EventArgs e)
{
int AnotherNumber= Int32.Parse(txtNumber.Text)+10;
}
You Must Change your Method's Structure to be like
public void doSomething(object sender, EventArgs e)
{
....
}
and for passing parameters you need a work around like this :
for example if you in an Html control you may but your parameter in an attribute value (such as ID in this exapmle) and then retrieve it in the server side handler
i.e to make an control changing the style color
Html :
<a href="" id="Grey" runat="server" onserverclick='ApplyStyleEvent'></a>
Code :
protected void ApplyStyleEvent(object sender, EventArgs e)
{
Profile["SelectedStyle"] = ((HtmlControl)sender).ID;
Response.Redirect("");
}
and so on.

Categories