Skip to main content
 首页 » 编程设计

c#之在不使用静态方法的情况下通过 Ajax 调用 c# 方法

2024年01月26日33kerrycode

我正在做一个必须使用 ajax 的网站,想知道是否有一种方法可以从服务器端调用方法,而无需将方法设置为静态。我对此进行了研究,但我发现的每个示例都将方法设置为静态,并且想知道您是否可以使用 static 这是我的代码

Ajax 代码:

function GetAddColour(id, Name) { 
 
    var dataValue = { "id": id, "Name": Name } 
 
    $.ajax({ 
        url: "AddColour.aspx/btnAddColour", 
        type: "POST", 
        dataType: "json", 
        data: dataValue, 
        contentType: "application/json; charset=utf-8", 
        success: function (msg) { 
            alert("Success"); 
        }, 
        error: function (e) { 
            alert(JSON.stringify(e)); 
        } 
    }); 
} 

C#代码:

[WebMethod] 
public static void btnAddColour(int id, string Name) 
{ 
    //do things to add colour 
} 

有没有没有静态方法的方法,而且我不能使用更新面板。

请您参考如下方法:

使用 ASP.NET AJAX 页面方法,您可以访问 Session 对象,因此如果您将登录的用户名存储在 Session["User"] 中,那么您可以做这样的事情:

代码隐藏:

[WebMethod(EnableSession = true)] 
public static string GetLoggedInUserName() 
{ 
    return HttpContext.Current.Session["User"].ToString(); 
} 

标记:

$.ajax({ 
    url: "AddColour.aspx/GetLoggedInUserName", 
    type: "POST", 
    dataType: "json", 
    data: "{}", 
    contentType: "application/json; charset=utf-8", 
    success: function (result) { 
        if (result.hasOwnProperty("d")) { 
            // Need to de-reference the JSON via the .d 
            alert(result.d); 
        } 
        else 
        { 
            // No .d; no de-reference necessary 
            alert(result); 
        } 
    }, 
    error: function (e) { 
        alert(JSON.stringify(e)); 
    } 
}); 

Note: The .d syntax was an anti-XSS protection put in by Microsoft in the ASP.NET 3.5 release of ASP.NET AJAX; therefore the check to see if the .d property is there or not.