4

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

The Score class:

public class Score
{
    // default constructor
    public Score()
    { }

    public int TraitID { get; set; }

    public double TraitScore { get; set; }
}

The ASPX WebMethod:

    [WebMethod]
    public static bool Test(List<Score> scores)
    {
        return true;
    }

The jQuery code:

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

            $.ajax({
                type: "POST",
                url: "Tryouts.aspx/Test",
                data: "{'scores':" + JSON.stringify(scoresList) + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d == true) {
                        alert("success!!!!!");
                    }
                    else {
                        alert("problem!!!!!!!!!");
                    }
                },
                error: function () {
                    alert("ERROR");  
                }
            });

I keep getting the error:

{"Message":"Cannot convert object of type \u0027System.String\u0027 to type
\u0027System.Collections.Generic.List`1[BusinessLogicLayer.Score]\u0027","StackTrace":"   at
System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type,
JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at
System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type,
JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at
System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary`2 rawParams)\r\n
at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target,
IDictionary`2 parameters)\r\n   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext
context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n   at
System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,
WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

Thanks !!!

1 Answer 1

6

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

another problem: how can I build the scoresList dynamically? Here is my code: $(".traits").each(function () { var selectedRadio = $(this).children('input[type=radio]:checked'); var score = selectedRadio.val(); if (score != undefined) { allScores += '{ TraitID: ' + selectedRadio.attr("name").replace('trait', '') + ', Score: ' + score + '}, '; } }); var scoresList = '[' + allScores.slice(0, -2) + ']'; How should look the data in the $.ajax ?
This really should be a separate question, but here goes : the string allScores string is not needed. add your score objects to your 'scoresList' var like this : ` $(".traits").each(function () { var selectedRadio = $(this).children('input[type=radio]:checked'); if (score != undefined) { scoresList.push( { TraitID: selectedRadio.attr("name").replace('trait', ''), Score: selectedRadio.val() }); } });`
var scoresList = []; $(".traits").each(function (){ var selectedRadio = $(this).children('input[type=radio]:checked'); var score = selectedRadio.val(); if (score != undefined) { scoresList.push({ TraitID: selectedRadio.attr("name").replace('trait', ''), Score: score }); } }); $.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 () { alert("ERROR"); } });
OMG Shane, I (and how many others) spent like 4 hours googling complicated solutions. And you nailed it, minimally and tightly-bound. Awesome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.