CinnamonBun
CinnamonBun

Reputation: 1150

json object binding in MVC

I seem to be having a problem passing a javascript object, which contains an array, to my MVC controller. I have an object which contains two strings, and a string array. The two strings bind correctly, but as soon as I add an array to the obect I get the following error:

Collection is read-only.

Here is my JS + Ajax code:

   $('.submit').on('click', function() {

        var viewModel = {
            FName: "John",
            LName: "Doe",
            DaysOfTheWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
        };

        console.log(viewModel);

        $.ajax({
            url: "/Home/JsonMethod",
            type: "POST",
            data: JSON.stringify(viewModel),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                console.log(data);
            }
        });

    });

Here is my MVC controller:

    public JsonResult JsonMethod(Person person)
    {
        return Json(person, JsonRequestBehavior.AllowGet);
    }

Here is the Person class:

    public class Person
    {
        public string FName { get; set; }
        public string LName { get; set; }
        public string[] DaysOfTheWeek { get; set; }

        public Person()
        {
            DaysOfTheWeek = new string[7];
        }
    }

I've had a look online, but I can't find anything that deals with the following issue. Any help with this matter would be great.

Upvotes: 3

Views: 3094

Answers (3)

Marko
Marko

Reputation: 13263

You need to change the property from:

public string[] DaysOfTheWeek { get; set; }

To:

public List<string> DaysOfTheWeek { get; set; }

Upvotes: 0

MisterJames
MisterJames

Reputation: 3326

List binding is simple and straightforward, but there are valid times (or uncontrollable times) to work with arrays as parameters on controller actions.

You can modify your $.ajax call to set the traditional parameter to true, which works with the expectations of the default model binder in the MVC Framework.

    $.ajax({
        url: "/Home/JsonMethod",
        traditional: true,
        type: "POST",
        data: JSON.stringify(viewModel),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            console.log(data);
        }
    });

More details and examples here: http://theycallmemrjames.blogspot.ca/2010/05/aspnet-mvc-and-jquery-part-4-advanced.html

Cheers.

Upvotes: 0

Eugene Yastrebov
Eugene Yastrebov

Reputation: 401

Problem might be because you've initialized array in your Person's constructor and when deserializer sees that there are already collection - it tries to add to it instead of create new one. Try to either remove initialization from constructor or change type to List.

Upvotes: 6

Related Questions