如何调用C#从JavaScript按钮点击的方法?

如何调用C#从JavaScript按钮点击的方法?

问题描述:

我试图从调用javascript函数一个服务器端的按钮单击方法,但它不工作,我可以知道我做错了?

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#按钮点击:

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();
    }

}

任何帮助将是AP preciated ..

Any help would be appreciated..

使用暴露的JavaScript __doPostBack方法。如果您在按钮和事件名称的ID传递,它本质上就像用户点击该按钮执行相同的回发到服务器。

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回传用JavaScript
(这里使用VB code-背后,却另有确实你需要什么,我认为)

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

编辑:只是为了澄清,而不是调用按钮的点击的方法,用__doPostBack而不是

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

EDITx2:另外,请确保您的OnClientClick返回值为true。如果是假的,我认为它等同于说这是不是有效,不应该做回发。

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.