3

I have a small working application in ASP.NET and C#, and I would like to add some JavaScript code to it.

I know that, for example, I can use the Confirm button and then do something on Yes or No.

I would like to 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?

2
  • 1
    Could you be more specific? Explain what you exactly want, what is are goals and requirements? Commented May 12, 2011 at 21:25
  • 1
    See this question: stackoverflow.com/questions/3713/… Commented May 12, 2011 at 21:26

3 Answers 3

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 code, in the confirm part of your code, simply do:

__doPostBack('TriggerMethod1', '');

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

Sign up to request clarification or add additional context in comments.

2 Comments

I personally use jQuery, and just trigger the click with: $("#TriggerMethod1").click();.
Thanks! This is what i was looking for. Clear and Concise!
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

2 Comments

The second link is broken: "Site not found"
@PeterMortensen FYI: There's a Wayback Machine save of that page that works if you want to fix the broken link. Unfortunately, the queue is full, so I can't.
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 a post back:

    function TriggerPostBack(control, arg){
        __doPostBack(control, arg);
    }
    
  4. Call the PostBack trigger function when needed:

     <a .... onclick="TriggerPostBack('control', 'arg')" .. /> 
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.