Shahar
Shahar

Reputation: 541

Posting a complex type from jquery to mvc

I have a complex type which looks like:

    public class ReviewProcessLevelModel {
             public int levelType;
             public string user;
             public string field;
             public string[] dtFieldValues;
             public string[] dtUsers;
    }

My posted string looks like (After JSON.stringify function):

     [
       {"levelType":0,"user":"71","field":null,"dtFieldValues":null,"dtUsers":null},
       {"levelType":1,"user":null,"field":"Dummy","dtFieldValues":null,"dtUsers":null}
     ]

My Controller looks like:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult saveCampaign(IList<ReviewProcessLevelModel> ReviewProcess)

And finally, this is how I send the data to the controller:

    $.ajax({
        type: "POST",
        url: "@Url.Action("saveCampaign", "SaasAccessCertification")",
        traditional: true,
        contentType: 'application/json',
        dataType: 'json',
        data: getRPData() // returns the string above
    }).done(function (resp) {
        debugger;
    }).error(function (resp) {
        debugger;
    });

The list comes with 2 ReviewProcessLevelModel but the objects are always with nulls.

Please advise and thank you for your time.

Upvotes: 3

Views: 1683

Answers (1)

David Spence
David Spence

Reputation: 8079

Right, three problems.

1 - The name of your parameter of your controller must match the name of the object your posting, so your json string turns into:

'{"ReviewProcess": [{"levelType": 0,"user": "71","field": null,"dtFieldValues": null,"dtUsers": null},{"levelType": 1,"user": null,"field": "Dummy","dtFieldValues": null,"dtUsers": null}]}'

2 - You should specify contentType as an option on your post:

contentType: 'application/json',

3 - It might sound crazy but your properties must have getters and setters.

public class ReviewProcessLevelModel
{
    public int levelType { get; set; }
    public string user { get; set; }
    public string field { get; set; }
    public string[] dtFieldValues { get; set; }
    public string[] dtUsers { get; set; }
}

I took your code, made those updates and then everything worked fine!

Upvotes: 4

Related Questions