2

I have this model with System.Runtime.Serialization attributes:

[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; }
}

And after that in Razor Model.DataTablesDescription (this is List<DataTableItemModel>):
@Html.Raw(new JavaScriptSerializer().Serialize(Model.DataTablesDescription))
or
@Html.Raw(Json.Encode(Model.DataTablesDescription))

Output HTML looks as:
[{"Targets":[0],"Visible":false,"Searchable":false,"Field":"Id"}, ...]

but I expected:
[{"targets":[0],"visible":false,"searchable":false,"name":"Id"},
i.e. subject to DataMember attributes.

What's wrong?

karavanjo
  • 1,626
  • 4
  • 18
  • 31
  • Might help http://stackoverflow.com/questions/6020889/asp-net-mvc-3-controller-json-method-serialization-doesnt-look-at-datamember-n – Satpal Apr 02 '15 at 10:13

2 Answers2

0

The problem is that the JavaScriptSerializer would not take your [DataMember]/[DataContract] into account.

Try to use the DataContractJsonSerializer:

For example:

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

serializer.WriteObject(memoryStream, Model.DataTablesDescription);

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

Alternatively, use Json.NET instead:

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

See MSDN

haim770
  • 48,394
  • 7
  • 105
  • 133
0

Can you try this?

[DataContract]
public class DataTableItemModel
{
    [DataMember]
    [DisplayName("targets")]
    public int[] Targets { get; set; }
}
F11
  • 3,703
  • 12
  • 49
  • 83