1..
1..

Reputation: 1

Some issues page has a querystring while using ajax

I have some problem ajax with query string, I can send the data if page does not have and Info.aspx/Save works great. But when I fill somethings with query string then post same data it will return http 500 error. I have nothing with querystring in javascript I use it in C# for id.

 var data = '{name: "' + $("input[name$='name']").val() +
                    '",description: "' + $("input[name$='description']").val() +
                    '",code: "' + $("input[name$='code']").val() +'"}';
$.ajax({
                type: "POST",
                url: "Info.aspx/Save",
                data: data,
                contentType: "application/json",
                dataType: "json",
                success: function (data) {
                    var result = data.d
                    console.log(result)
                    if (result > 0)
                        success.show();
                    else
                        error.show();
                    Metronic.scrollTo(error, -200);

                },
                error: function () {
                    console.log('err')
                }
            });

    [WebMethod]
    public static int Save(string name, string description, string code)
    {
        ClassInfo classInfo = new ClassInfo();
        return ClassInfo.Save(name, code, description, FileInfo.id);
    }

I just use querystring in C# for filling inputs. Altough I send same data it works without querystring inpgae's adressbar, If it has querystring in addressbar ajax returns me http500 error and Save WebMethod does not work.

Upvotes: 0

Views: 294

Answers (1)

Hamix
Hamix

Reputation: 1335

data types must be object, no string.

var data = {name: $("input[name$='name']").val() ,description:$("input[name$='description']").val(),code:$("input[name$='code']").val()};

Remove the contentType or change it to

"application/x-www-form-urlencoded; charset=utf-8"

Then

$.post('/Info.aspx/Save',data , 
   function (data) {   
});

Or

$.ajax({
    url: '/Info.aspx/Save',
    data: data 
});

Server side Your json parameter names must be same with the c# paramter names.

[WebMethod(true)]
public static string Save(string name, string description, string code)
{
    return name+" "+description+" "+code;
}

Usable for Web Method and Query String(working for both)
The query string parameters need to be passed as JSON.

data: JSON.stringify({ "name": "name", "description": "description","code":"code" }),
contentType: "application/json; charset=utf-8"

Server side

[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static String Save(string name, string description, string code)
{
}

Upvotes: 1

Related Questions