samedi 26 novembre 2016

Passing Data From Ajax Call to C# Web Method

We would like to send the contents of a web form with ajax call to a web method, which in turn calls a web service to insert the form contents to the database. We do not use MVC, but use our custom c# code.

Our javascript is as folllows:

        var data = {
            HT: $("input[name='HT']").val(),
            KT: $("input[name='KT']").val(),
            T: $("input[name='T']").val()
        };
        $.ajax({
            type: "POST",
            url: "LTCreate.aspx/Create",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(data),
            async: true,
            success: function(msg) {
                alert(msg.d);
            }
        });

Our c# code is as follows:

        [WebMethod(EnableSession = true)]
        public static string Create(string strJson)
        {             


                 HT = JsonConvert.DeserializeObject<pb.CLS_HT>(strJson);

         ret = ws.INSERT_HT(SYSTEM_CODE, USER_INFO, HT, ref errMsg);
         if (ret < 0)
         {
             return ret.ToString() + " " + errMsg;
         }
         else
         {
             return ret.ToString();
         }
       }

When we run the above code, we get the following error message: Message: "Invalid web service call, missing value for parameter: 'strJson'.",… Stack Trace: at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters) ↵ at System.Web.Script.Services.RestHandler.InvokeMethod

How could we properly get the contents of data string in c# web method?

Thank you.




Aucun commentaire:

Enregistrer un commentaire