简体   繁体   中英

Calling a c# method trough Ajax without using static methods

I am doing a website where I have to use ajax and was wondering if there is a way to call a method from the server side with out setting the method to static. I researched this but every example I found has the method set as static and was wondering if you could this with using static here is my code

Ajax Code:

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));
        }
    });
}

The C# code:

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

Is there a way to this without static method and also I cannot use update panels.

Using ASP.NET AJAX Page Methods you can access the Session object, so if you store your logged in user name in Session["User"] , then you could do something like this:

Code-behind:

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

Markup:

$.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.

Assuming you're using web forms rather than ASP.Net MVC, you can create a *.ashx HttpHandler. It's just like a *.aspx page, but much much simpler. Your code-behind just has to implement the IHttpHandler interface (1 method, ProcessRequest() and 1 property IsReusable ). If you require access to session state, you'll also need to "implement" (a misnomer, since these are both marker interfaces with nothing to implement) either IReadonlySessionState (read-only access) or IRequiresSessionState (read/write access).

However, you're responsible for pretty much everything from soup to nuts here. You can return JSON, binary image data, whatever your little heart desires.

modify your datavalue to this.

var dataValue = "{id :'" + id + ", Name :'"+ Name "'}" ;

where id and name are two variables which have integer and string value respectively. Ensure id to be integer, if it is not then change it to Number(id)

Javascript :

function GetAddColour(eid, eName) {
   var id = Number(eid);
   var Name = eName;
   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 () { alert(arguments[2]); }      
        });
 }

and your C# web method should be

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void btnAddColour(int id, string Name)
{
    // Your code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM