admin管理员组

文章数量:1315981

How to call javascript function and code behind function using button?

<asp:button id="btnSave" onclick="btnSave();" onclientclick ="return javascriptfunction();" runat="server">

</asp:button>

I tried like this too. but no response.

<asp:button id="btnSave" onclick="btnSave();" onclientclick ="return true;" runat="server">

</asp:button>

even, javascript function return true, its not calling codebehind function. May i know reason?

How to call javascript function and code behind function using button?

<asp:button id="btnSave" onclick="btnSave();" onclientclick ="return javascriptfunction();" runat="server">

</asp:button>

I tried like this too. but no response.

<asp:button id="btnSave" onclick="btnSave();" onclientclick ="return true;" runat="server">

</asp:button>

even, javascript function return true, its not calling codebehind function. May i know reason?

Share Improve this question edited Mar 28, 2013 at 22:19 Tim 1,8262 gold badges23 silver badges35 bronze badges asked Mar 28, 2013 at 21:57 mayilmayil 111 gold badge1 silver badge3 bronze badges 2
  • Are you using C# or VB? Also, you also need to expand upon what you are trying to acplish. Are you trying to just simply call both regardless? Are you trying to call the JS method and only call the CodeBehind method if the JS method returns true? Etc. – Code Maverick Commented Mar 28, 2013 at 22:00
  • Look at : stackoverflow./questions/2155048/… – Sinan AKYAZICI Commented Mar 28, 2013 at 22:11
Add a ment  | 

2 Answers 2

Reset to default 3

The code should be something like this -

JavaScript:

<script>
    function save() 
    {
        return confirm('Are you sure you want to continue?');            
    }
</script>

ASPX:

<asp:Button ID="btnSave" OnClick="btnSave_Click" OnClientClick="return save();" 
   runat="server" />

C# CodeBehind:

protected void btnSave_Click(object sender, EventArgs e)
{
   // Do something
}

It basically call JavaScript function before posting back to server. Whether post back to server or not is depending upon the return value from JavaScript function.

Button control's OnClick is an server side event so you need to attach to server side click event.

The best way I have found to do this is from code behind using RegisterStartupScript

 ScriptManager.RegisterStartupScript(this, this.GetType(), "name", "javascriptfunction();", true);

本文标签: aspnetHow to call javascript function and code behind using buttonStack Overflow