Sayamima
Sayamima

Reputation: 225

calling a javascript function in C#

Hi i wanted to show or hide duplicate records according to query. So, I need to know how to call the javascript function from C# codebehind.

  <a onclick="Grid1.insertRecord(); return false;" id="a2"  href="javascript:">Save</a>

When I click save i need to show a popup which i have written in javascript.

 if (!exist)//exists is the query
        {
            System.Web.UI.Control my = FindControl("a2");
              a2.Attributes.Add("onclick", "retrun HideDuplicate()");

This line returns an error saying "a2 doesnot exist in current context."

Upvotes: 2

Views: 1026

Answers (3)

JustinC
JustinC

Reputation: 415

MSDN documentation for programatic creation of client side callbacks without postback with an example where the code behind is in C# might give a good overview of how it is supposed to work in general.

In your case, the corresponding code-behind should implement the interface 'ICallbackEventHandler' and the two methods it describes. In addition, you would need two more client side Javascript functions to prepare and handle the callback, besides the executor/invoker (in your case, a 'save' method). However one of the additional two Javascript functions could be registered in the codebehind, as the example shows.

Upvotes: 1

rtpHarry
rtpHarry

Reputation: 13135

The basic <a> tag is not turned into a control by asp.net unless you add a runat="server" to it. Its then turned into a HtmlGenericControl.

<a onclick="Grid1.insertRecord(); return false;" id="a2" href="#" runat="server">Save</a>

This might work for you - its not clear if you have more than one of these links on the page (such as in a row of a gridview?) or if its just on there once.

Also the way you have used javascript is not following best practices but thats a discussion for another day :)

Upvotes: 1

Bala R
Bala R

Reputation: 109037

Why not use an asp.net LinkButton? It has a server side Click event and is accessible from c# code-behind.

Upvotes: 1

Related Questions