locked
ajax submit a object and how to get it in code behind C# RRS feed

  • Question

  • User-800465396 posted
         $(document).ready(function () {
                $("#login").click(function () {
    
                    var username = $("#username").val();
    
                    var password = $("#password").val();
    
                    var user = '{ "username":"' + username + '", "password": "' + password + '" }';//这里,就是将数据封装成json
                   
                    $.ajax({
                        type: "POST",
                        cache: false,
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        url: 'http://localhost:16620/WebForm1.aspx/User2',
                        data: user ,
                        success: function (result) {
                            alert(result.d);
    
                        },
    
                        error: function (err) {
    
                            alert(err.error());
    
                        }
                 
                    })
                })
            })
     <form id="form1" runat="server">
        <div>
            <p>username<input type="text" id="username"/></p>
            <p>password<input type="text" id="password" /></p>
           <input type="button" id="login" value="提交"/>
            
        </div>
        </form>
     
     [WebMethod(true)]
     public static string User2(string username,string password)  //work well
            {
               
            }
    
    [WebMethod(true)]
     public static string User2(string json) //don't wrok,how to let this work as a json string. Because,this could prevent the params are too many.
            {
               
            }




    Friday, January 30, 2015 4:01 AM

All replies

  • User-1509636757 posted

    To get these json parameters in the Web Method, you should define the web method definition with the same parameter names as defined in the string created above. That is why public static string User2(string username,string password) works as expected because  you have same name and numbers of parameters defined in web method which you are passing from jquery Ajax post.

    hope it helps./.

    Friday, January 30, 2015 5:11 AM
  • User-800465396 posted

    no help. i need sample

    Tuesday, February 3, 2015 1:23 AM