jquery problem with sending json data to ASP.NET WebMethod

前端 未结 1 1174
长情又很酷
长情又很酷 2021-01-03 09:22

I\'ve read all the questions regarding this issue but didn\'t manage to solve it...

The Score class:

public class Score
{
    // default constructor
         


        
相关标签:
1条回答
  • 2021-01-03 09:46

    I'm passing arrays of custom objects into List in web methods and it works just fine.

    I'm, guessing that you're having a small JSON formatting issue because of the quotes around the property names. Try changing your object to this :

    var scoresList = [{TraitID:1, TraitScore:2}, {TraitID:2, TraitScore:5}];
    

    and change your data line to this :

    data: JSON.stringify({ scores : scoresList }),      
    

    Hope that helps...

    UPDATE: working example...

    <script type="text/javascript">
    $(function () {
    
        var scoresList = [{ TraitID: 1, TraitScore: 2 }, { TraitID: 2, TraitScore: 5}];
    
        $.ajax({ type: "POST",
            url: "Tryouts.aspx/Test",
            data: JSON.stringify({ scores: scoresList }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                if (response.d == true) {
                    alert("success!!!!!");
                } else {
                    alert("problem!!!!!!!!!");
                }
            },
            error: function (xhr) {
                alert("ERROR");
            }
        });
    
    });
    </script>
    

    Here's the codebehind :

    public class Score
    {    // default constructor    
        public Score() { }
        public int TraitID { get; set; }
        public double TraitScore { get; set; }
    }
    
    [WebMethod]
    public static bool Test( List<Score> scores )
    {
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题