简体   繁体   中英

JSON doesn't get parsed by MVC

I have the following C#:

Model:

namespace WebInventory.Models
{
    [DataContract]
    public class PostbackList
    {
        [DataContract]
        public class Field
        {
            public int ID;
            public string Name;
            public int DataTypeID;

            public bool Checked;
        }

        [DataMember]
        public int TypeID;

        [DataMember]
        public IList<Field> Fields;

        [DataMember]
        public IList<IList<string>> Values;

        #region Non DataMember
        public IList<int> UsedFieldsID;
        #endregion
    }
}

Controler:

public class ListController : JsonController
{
    [HttpPost]
    public ActionResult GetList(PostbackList data)
    {
        <...>
    }
}

And I send the following JSon object:

{"TypeID":16,"Fields":[{"ID":42,"Name":"","DataTypeID":0,"Checked":true},{"ID":43,"Name":"","DataTypeID":0,"Checked":true},{"ID":44,"Name":"","DataTypeID":0,"Checked":true}],"Values":null}

using:

    $.ajax({
        url: url
        , type: 'POST'
        , dataType: 'json'
        , contentType: 'application/json; charset=utf-8'
        , data: JSON.stringify(parameter)
        , xhrFields: {
            withCredentials: true
        }
    })
    .done(function (data) {
        fillTemplate(data);
    });

I set a breakpoint inside MVC GetList and there I see data is uninitialized. I tried using arrays instead of (I)List but it didn't help.

I can't see what's wrong.

I think you should use properties instead of fields.

I had the same issue recently where the model binder wasn't picking up my json.

I changed to properties instead.

public int ID {get; set;}

change all your fields to properties as below.

namespace WebInventory.Models
{
    [DataContract]
    public class PostbackList
    {
        [DataContract]
        public class Field
        {
            public int ID {get; set;}
            public string Name {get; set;}
            public int DataTypeID {get; set;}

            public bool Checked {get; set;}
        }

        [DataMember]
        public int TypeID {get; set;}

        [DataMember]
        public IList<Field> Fields {get; set;}

        [DataMember]
        public IList<IList<string>> Values {get; set;}

        #region Non DataMember
        public IList<int> UsedFieldsID {get; set;}
        #endregion
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM