user1764195
user1764195

Reputation: 43

How do you pass a string to C#/ASP.NET using $.ajax()?

This works

[System.Web.Services.WebMethod]
public static string Save_HH()
{
    return "abc";
}

This does not work

[System.Web.Services.WebMethod]
public static string Save_HH(string myString) // (int i, string s) (object o) etc
{
    return "abc";
}

This is the ajax call

$.ajax({
    type: "POST",
    url: "Default.aspx/Save_HH",
    data: {}, // data: JSON.stringify({abc:123}),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        btn.css("visibility", "visible");
        $("#ta_response").text(response.d);
    },
    fail: function () {
        alert("fail");
    },
});

This error message is POST localhost(cant post link on my new account)/Default.aspx/Save_HH 500 (Internal Server Error)


At this point the question seems fairly clear and concise but I was just prevented from posting it as is. I don't want to say anything more because I think it is a well formed question and saying anything else would make the reader confused.

Upvotes: 3

Views: 3313

Answers (2)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102438

If you replace this:

data: {}, // data: JSON.stringify({abc:123}),

with this:

data: { myString : "test" }

it should work out of the box.

Just remember that the name and type of the parameter you're passing through the $.ajax call must match the parameter name and type you declared in the WebMethod. Otherwise the binding won't occur and your myString parameter will be null (in the case of a string type) inside the WebMethod Save_HH.

Upvotes: 3

Ravindra Bagale
Ravindra Bagale

Reputation: 17675

jQuery.ajax( url [, settings] )

url A string containing the URL to which the request is sent.
settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().

Upvotes: 0

Related Questions