Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 944
user1764195 Avatar asked Dec 05 '25 18:12

user1764195


1 Answers

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.

like image 103
Leniel Maccaferri Avatar answered Dec 07 '25 08:12

Leniel Maccaferri