枚举不绑定到ASP.NET JSON请求中的属性

时间:2014-02-04 18:25:57

标签: asp.net-mvc json enums json.net model-binding

我不确定为什么我的类型ScheduleType的枚举不会绑定到下面json中的属性Type。其他属性绑定查找,我没有在其他地方有枚举绑定的问题,想法?它始终默认为第一个。

JSON

{"Id":0,"BulkInsertId":null,"DivisionId":10406,"DivisionName":"17","DivisionOrder":1,"Type":1,"Name":"A1 vs. A2" }

public class ScheduleMatchupModel : IScheduleMatchupModel
    {
        public ScheduleType Type { get; set; }

        public int Id { get; set; }
        public int DivisionId { get; set; }
        public int? DivisionOrder { get; set; }
        public string DivisionName { get; set; }

IScheduleMatchupModel.cs

public interface IScheduleMatchupModel
{
    int Id { get; set; }
    ScheduleType Type { get; set; }

ScheduleType枚举

[DataContract(Namespace = "")]
public enum ScheduleType
{
    [EnumMember(Value = "0")]
    All = 0,
    [EnumMember(Value = "1"), Display(Name = "Pool Play")]
    Pool,
    [EnumMember(Value = "2"), Display(Name = "Bracket Play")]
    Bracket
}

1 个答案:

答案 0 :(得分:2)

通过EnumMember属性,您可以为枚举设置特定值:

[EnumMember(Value = "0")]
All = 0,
[EnumMember(Value = "1"), Display(Name = "Pool Play")]
Pool,
[EnumMember(Value = "2"), Display(Name = "Bracket Play")]
Bracket

唯一的问题是EnumMember属性的Value属性是一个字符串:

public string Value { get; set; }

并在JSON中为整数分配整数:

{...,"Type":1,... }

因此,您应该尝试将其更改为JSON中的字符串:

{..."Type":"1",... }