0

How to call function in code-behind in c# with javascript?

I have this code behind :

protected void btn_Click(object sender, EventArgs e)
{
    if (btn != null && btn.Checked)
    {
        Response.Redirect(string.Format("get.aspx?a={0}&b={1}", 
                                         a.SelectedValue, b.SelectedValue));
    }
}

And I have a Checkbox :

<asp:CheckBox ID="btn" runat="server" Checked="false" />

I am tryong to call that function btn_Click in javascript :

var btn = document.getElementById("btn");

if (btn.checked) {
    '<% = btn_Click() %>'
}

But not worked!!! Why? Thanks.

Jegadeesh
  • 335
  • 2
  • 16
Hamamelis
  • 1,983
  • 8
  • 27
  • 41
  • this might help you http://stackoverflow.com/questions/3713/call-asp-net-function-from-javascript – Avinash patil Mar 25 '14 at 13:41
  • try this document.getElementById('<%=btn.ClientID %>') and see if that works.Also alert(btn) and see if its not returning null. Also you need to do postback to call server side btn_click event. – rach Mar 25 '14 at 13:43

2 Answers2

1

You can do a proper ajax approach explained here -> http://www.techillumination.in/2013/07/an-aspnet-way-to-call-server-side.html

TBAR
  • 448
  • 2
  • 10
0

you can do it like this using Jquery, This is not tested

var button = $("#btn");
$(button).trigger("click");
Amarnath R Shenoy
  • 5,121
  • 8
  • 24
  • 32