TruMan1
TruMan1

Reputation: 36128

DateMember needed in models for Web API?

Sometimes my models require me to decorate the properties with DataMember and other times not. Otherwise, the properties are null through web services. I have not figured out why or what the pattern of when to add the attribute and when not to. Is it when I have inherited models? Perhaps when I have models as properties of other models? When should I do this or should I always add the attribute on my properties?

Upvotes: 0

Views: 45

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039220

The DataMember is useful when you want to use a different name for your property in the model to the value being sent in the request Payload. It basically gives you some control over the serialization.

For example:

[DataMember(Name = "first_name")]
public string FirstName { get; set; }

Also IIRC if you specify DataMember on one property you should specify it for all properties (even if you do not override the name) and also decorate your model with the [DataContract] attribute.

Upvotes: 1

Related Questions