2015-04-02 52 views
2

我有這個模型System.Runtime.Serialization屬性:數據成員屬性不是JSON影響導致

[DataContract] 
public class DataTableItemModel 
{ 
    [DataMember(Name = "targets")] 
    public int[] Targets { get; set; } 
    [DataMember(Name = "visible")] 
    public bool Visible { get; set; } 
    [DataMember(Name = "searchable")] 
    public bool Searchable { get; set; } 
    [DataMember(Name = "name")] 
    public string Field { get; set; } 
} 

而在這之後的剃刀Model.DataTablesDescription(這是List<DataTableItemModel>):
@Html.Raw(new JavaScriptSerializer().Serialize(Model.DataTablesDescription))

@Html.Raw(Json.Encode(Model.DataTablesDescription))

輸出HTML看起來:
[{"Targets":[0],"Visible":false,"Searchable":false,"Field":"Id"}, ...]

,但我預計:
[{"targets":[0],"visible":false,"searchable":false,"name":"Id"},
即受到數據成員屬性。

怎麼了?

+0

可能有助於http://stackoverflow.com/questions/6020889/asp-net-mvc-3-controller-json-method-serialization-doesnt-look-at-datamember-n – Satpal 2015-04-02 10:13:19

回答

0

問題是JavaScriptSerializer不會考慮您的[DataMember]/[DataContract]

嘗試使用DataContractJsonSerializer

例如:

@{ 
var serializer = new DataContractJsonSerializer(typeof(DataTableItemModel)); 
var memoryStream = new MemoryStream(); 

serializer.WriteObject(memoryStream, Model.DataTablesDescription); 

@Html.Raw(new StreamReader(memoryStream).ReadToEnd()) 
} 

另外,使用Json.NET代替:

@Html.Raw(JsonConvert.SerializeObject(Model.DataTablesDescription)); 

MSDN

+0

Json.NET完美使用DataMember屬性。謝謝。 – karavanjo 2015-04-02 10:45:03

0

你可以試試這個?

[DataContract] 
public class DataTableItemModel 
{ 
    [DataMember] 
    [DisplayName("targets")] 
    public int[] Targets { get; set; } 
}