我有System.Runtime.Serialization属性的这个模型:
[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; }
}
之后在Razor 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"},
即受DataMember属性约束。
怎么了?
答案 0 :(得分: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
答案 1 :(得分:0)
你能试试吗?
[DataContract]
public class DataTableItemModel
{
[DataMember]
[DisplayName("targets")]
public int[] Targets { get; set; }
}