Reputation: 3799
i am using MVC c# i have a object with
public class Person
{
public int TypeId { get; set; }
public string Code { get; set; }
}
i have a code that retruns JSON object for this object like this
return Json(personCodeStore.GetBusinessCodes());
But when I receive this on the client side i want to be able to rename the field name from
TypeId to value
Code to text
I do not want to use DataContractSerializer like MVC3 JSON Serialization: How to control the property names? because i am using EF 5.x and every time i update the model and .tt file runs it overwrites my changes and also it uses this modified property on all my views which i don't want.
So is there a way i can rename this when i serialize it or once i get on client side using jquery?
Upvotes: 0
Views: 1766
Reputation: 1039528
You could simply use LINQ and return an anonymous object projecting your original result:
var businessCodes = personCodeStore.GetBusinessCodes();
return Json(businessCodes.Select(x => new
{
value = x.TypeId,
text = x.Code
}));
Now you're gonna get something along the lines of:
[
{ "value": 1, text = "text 1" },
{ "value": 2, text = "text 2" },
{ "value": 3, text = "text 3" }
...
]
Upvotes: 3