最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ASP.NET call C# functions from JavaScript - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Sep 15, 2023 at 15:58 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked May 12, 2011 at 21:22 NicoTekNicoTek 1,1671 gold badge14 silver badges34 bronze badges 2
  • 1 Could you be more specific? Explain what you exactly want, what is are goals and requirements? – Caspar Kleijne Commented May 12, 2011 at 21:25
  • 1 See this question: stackoverflow./questions/3713/… – Aaron Daniels Commented May 12, 2011 at 21:26
Add a ment  | 

3 Answers 3

Reset to default 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.

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

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')" .. /> 
    
发布评论

评论列表(0)

  1. 暂无评论