3

I Have a small working application on ASP.NET and C# and I would like to add some Javascript to it.

I know that for example I can use the Confirm button and then do something on yes or no.

What I would like to do is call some of the functions I have in the code-behind, depending on the answer to the Confirm Button.

How do I go about this? Many Thanks!

NicoTek
  • 1,045
  • 1
  • 14
  • 33

4 Answers4

3

Simple.

Put a hidden div on your aspx page that contains button triggers to your methods:

<div style="display: none">
     <asp:Button ID="TriggerMethod1" runat="server" />
</div>

In your javascript, in the confirm part of your code simply do:

__doPostBack('TriggerMethod1', '');

And in your code-behind, handle up that button click to call Method1.

Code Maverick
  • 19,661
  • 10
  • 58
  • 112
1

I would create an ASHX handler file and post back to the hander using jQuery ajax methods.

See an article on this here:

Using jQuery in ASP.NET apps with httphandlers

Mike Marshall
  • 7,740
  • 4
  • 38
  • 62
1

To call a server side method on a client side event you need to do the following:

1- Create the server side method:

void DoSomething(...) { ... }

2- Implement the System.Web.UI.IPostBackEventHandler.RaisePostBackEvent which take one string argument (You can assign the name to the value of this argument).:

public void RaisePostBackEvent(string eventArgument) 
{
        DoSomething(...);
}

3- Write a script to trigger post back:

function TriggerPostBack(control, arg){
    __doPostBack(control, arg);
}

4- Call the PostBack trigger function when needed:

<a .... onclick="TriggerPostBack('control', 'arg')" .. /> 
Akram Shahda
  • 14,295
  • 4
  • 43
  • 64
0

Have you tried to use the search first in the site!! Call ASP.NET function from JavaScript? Calling functions from an ASP.NET code file with javascript

or https://stackoverflow.com/search?q=Call+C%23+Functions+From+JavaScript

Community
  • 1
  • 1
Ahmed Magdy
  • 5,576
  • 8
  • 40
  • 74