1
votes

I has write a webmethod using c#, the web method as below

  [WebMethod]
    public string getname(string name)
    {
        return "my name is" + name.ToString();
    }

I create another aspx page to call the web method. If i set the dataType and contentType, it keep return me an error and alert fail. If I remove the contentType and datatype, it alert me OK. But when I alert(data) which is return data from web method, it show me all the html code of the page I created. I check the browser console, it show me POST http://webservice.aspx/getname 500 (Internal Server Error). What the error I make. Please help.

 function getname()
    {            
        var name = "Peter";
        $.ajax({
            url: '/webservice.aspx/getname',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: "POST",
            data: "{'name':" + name + "}",
            success: function (data) {
                alert("OK");
                alert(data);
            },
            error: function (result) {
                alert("fail");
            }
        });
    }
2
If you are using web method in aspx page it must be static.Modify it -----public static string getname---Sam

2 Answers

0
votes

Try this:

function getname()
    {            
        var name = "Peter";
        $.ajax({
            url: '/webservice.aspx/getname',
            //contentType: "application/json; charset=utf-8",
            //dataType: "json",
            type: "POST",
            data: {name:name}
            success: function (data) {
                alert("OK");
                alert(data);
            },
            error: function (result) {
                alert("fail");
            }
        });
    }
0
votes

dataType is define what type the data come in ( to javascript). Not the type the data you sent.

in js: data: { name: name },

in WebMethod: return Json.Encode(xxx);