简体   繁体   中英

Calling javascript and C# on button/link click

I currently have a Gridview with a itemTemplate which acts as a link which calls a javascript function:

 <ItemTemplate>
            <a href="javascript:;" onclick="simpleCart.add( 'name=<%# Eval("Name") %>' , 'price=<%# Eval("Price") %>' , 'quantity=1' );">Add To Cart</a>
            </ItemTemplate>

I need to add some functionality which I can only do in C#, so I was thinking of replacing the link with a button and when the button is clicked it calls both the C# function and the javascript function (they don't need to interact/share any data). Is this even possible?

You could use a LinkButton and set the OnClientClick property to execute a javascript function before going to the server. You could even cancel the server call if you return false from this function:

<asp:LinkButton 
    id="LinkButton1"
    text="Add To Cart"
    OnClientClick='<%# string.Format("&quot;name={0}&quot;, &quot;price={1}&quot;, &quot;quantity=1&quot;", Eval("Name"), Eval("Price")) %>'
    OnClick="LinkButton1_Click"
    runat="Server" />

You can use OnClientClick properyy of LinkButton in order to execute client script and OnClick event for server code

Here is code example and more detailed description http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton.onclientclick.aspx

Yes, it's possible.

It sounds like you want to avoid a full-page postback, so you could call the server-side code either with an ASP.NET Callback or with a more vanilla Ajax call, perhaps using jQuery. (I'm assuming your C# code is on the server, rather than in a local Silverlight app).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM