Call C# Function From JavaScript/JQuery In Asp.net webforms

前端 未结 5 1324
南旧
南旧 2021-01-19 06:33

So, i have an aspx page which looks like this:

<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"_Default\" %>
         


        
5条回答
  •  抹茶落季
    2021-01-19 06:58

    One way to call a C# method from client using JavaScript is using webmethods.

    You need to define a public static method in your code behind and add to it the [WebMethod] attribute.

    In this example I used a WebMethod that returns the current datetime as a string from the server:

    [WebForm1.aspx.cs]

    using System;
    using System.Web.Services;
    
    namespace TemplateWebMethod
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            [WebMethod]
            public static string MyMethod()
            {
                return DateTime.Now.ToString();
            }
        }
    }
    

    In the aspx page form you need to add an asp:ScriptManager with EnablePageMethods="true":

    [WebForm1.aspx]

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TemplateWebMethod.WebForm1" %>
    
    
    
    
    
        
        
    
    
        

    For Button1:

    ClientIDMode="Static" is used so Button1 will have same ID on client-side and we can search for it easily when adding client-side onclick.

    UseSubmitBehavior="false" is required so that pressing the button will not cause a full postback.

    In this example the WebMethod MyMethod will be called from codebehind by pressing Button1 so we set the onclick behavior for Button1 on window.onload:

    window.onload = function(){
      document.getElementById('Button1').onclick = function() {
        PageMethods.MyMethod(myMethodCallBackSuccess, myMethodCallBackFailed);
      }
    }
    

    Where:

    PageMethods.MyMethod(myMethodCallBackSuccess, myMethodCallBackFailed);
    

    is the JavaScript method that calls the server side code.

    We need to define its 2 callback methods for success and failure.

    On success we popup a message with the returned value from MyMethod:

    function myMethodCallBackSuccess(response) {
        alert(response);
    }
    

    On failed we popup a message with the error message:

    function myMethodCallBackFailed(error) {
        alert(error.get_message());
    }
    

提交回复
热议问题