govin
govin

Reputation: 6693

ASP.NET MVC model binding - different names for JSON property and C# model properties

I've annotated the properties of my model classes as below.

[DataMember(Name = "EN")]
public string EmployeeName{ get; set; }

This overall results in a compact JSON (I'm serializing using JSON.NET serializer).

However when JSON containing these smaller names is passed using a POST or a PUT request to the controllers, ASP.NET MVC model binding is not able to correctly map the "EN" JSON property to EmployeeName. It expects EmployeeName in JSON.

Any thoughts on how to fix this?

Upvotes: 4

Views: 1918

Answers (1)

Sergei Rogovtcev
Sergei Rogovtcev

Reputation: 5832

You can't do that out-of-the box. You have two ways of solving this: either renaming properties in your viewmodel (after all, it is a view model, so it has to cope with your restrictions) or you can try writing your own ModelBinder which will take DataMember annotations into consideration when binding properties.

Upvotes: 4

Related Questions