Matt
Matt

Reputation: 3970

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?

Upvotes: 0

Views: 2173

Answers (3)

Nastya Kholodova
Nastya Kholodova

Reputation: 1321

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

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

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" />

Upvotes: 1

RickNZ
RickNZ

Reputation: 18654

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).

Upvotes: 0

Related Questions