5

i am trying to call a server side button click method from javascript function but it's not working, can i know where i did wrong?

aspx code:

<asp:Button ID="ButtonFns" Name="ButtonFns" runat="server" Text="Finish" 
            OnClientClick ="CountDownTick()" class="finish" onclick="ButtonFns_Click" />

Javascript code:

function CountDownTick() {
if (_currentSeconds <= 0) {
    document.getElementById('<%= ButtonFns.ClientID %>').click();        
return;
}   
SetCountdownText(_currentSeconds-1);
window.setTimeout("CountDownTick()", 1000);
}

C# button click:

protected void ButtonFns_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Examination.mdf;Integrated Security=True;User Instance=True");
    try
    {
        con.Open();
        string snm;
        string Em;
        string Sx;
        string uname = Session["status"].ToString();
        string qry = "SELECT SName,Email,Sex FROM Students WHERE Uname=@uname";
        SqlCommand cm = new SqlCommand(qry, con);
        cm.Parameters.AddWithValue("@uname", uname);
        SqlDataReader reader = cm.ExecuteReader();
        while (reader.Read())
        {
            snm = reader["SName"].ToString();
            Em = reader["Email"].ToString();
            Sx = reader["Sex"].ToString();
            if (snm != null && Em != null && Sx != null)
            {
                Session["snm"] = snm.ToString();
                Session["em"] = Em.ToString();
                Session["sx"] = Sx.ToString();
                Session["uname"] = uname;
                Session["RAns"] = LabelRitAns.Text;
                Session["Tatt"] = LabelTotAtt.Text;
                Server.Transfer("YourScore.aspx");
                break;
            }
        }

    }
    catch (Exception emsg)
    {
        LabelErr.Text= emsg.Message.ToString();
    }
    finally
    {
        con.Close();
    }

}

Any help would be appreciated..

Abhishek
  • 89
  • 1
  • 3
  • 10
  • What does "It's not working" mean exactly? Noone here is a mind reader. – asawyer May 07 '12 at 12:11
  • @Abhishek , please understand that your button is a server side control , so you cannot call a code behind method just the way you did. – Priyank Patel May 07 '12 at 12:23
  • Is the Javascript rendered correctly in the browser? Do you get any errors? Have you tried setting a breakpoint in CountDownTick()? – mgnoonan May 07 '12 at 12:26
  • Where are you reducing the value of `_currentSeconds`? –  May 07 '12 at 12:31

5 Answers5

6

Use the __doPostBack method exposed for JavaScript. If you pass in the ID of the button and event name, it essentially performs the same postback to the server as though the user clicked the button.

ASP.NET postback with JavaScript (this uses VB code-behind, but otherwise does what you need I think)

EDIT: Just to clarify, instead of calling the button's "click" method, use __doPostBack instead.

EDITx2: Also, make sure your OnClientClick return value is true. If it's false, I think its equivalent to saying it's not valid and should not do a postback.

Community
  • 1
  • 1
Chris Sinclair
  • 22,858
  • 3
  • 52
  • 93
2
ButtonFns.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(ButtonFns, "Your postback argument"));

GetPostBackEventReference allows you to get that piece of JavaScript, so that you can trigger that postback from elsewhere.

This article will help you to resolve this issue

How to call Postback from Javascript

Eugene Trofimenko
  • 1,611
  • 1
  • 13
  • 19
1

You can make a POST request from your client side firstly make your click event to method as:

[WebMethods]
public static void ClickEvent()
{
//do you stuff
}

and now make an ajax call from your client side let your web page name is Default.aspx:

$.ajax({
  type: "POST",
  url: "Default.aspx/ClickEvent",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
1

In your case you can do it like that,

    <script type="text/javascript">

    function ImitatePressButton() {
            __doPostBack('ButtonFns', '');
    }
</script>

good luck.

Alper
  • 771
  • 1
  • 9
  • 27
0

If you want to call a button from javascript, here is another way how.

 var test = document.getElementbyId("YourButtonName");

 test.onclick = function() {
        //your code
javasocute
  • 648
  • 2
  • 11
  • 28