Returning JSON is very simple in ASP.NET MVC:

 return Json(Person, JsonRequestBehavior.AllowGet);

(Person is an Entity Framework object) The problem with this is if Person have related objects, like e.g. Friends. Then the serializer will throw an error because it will get a circular reference when tying to serialize Person. So one common solution is to just create a new anonymous object on the fly like so:

return Json(new {Name = Person.Name, Age = Person.Age}, JsonRequestBehavior.AllowGet);

A second solution is to create a Poco class that you fill with data from the entity object. A third solution is to "tag" your model members with Attributes. But you cannot do this with an EF class, since the codefile is autogenerated, and if you change the code then your changes will be overwritten the next time you use the designer. The following code demonstrates how to make this work anyway.

 public class PocoAttribute: System.Attribute {}[MetadataType(typeof(PersonMeta))] public partial class Person {}
 public class PersonMeta {
     [Poco] public string Name {
         get;
         set;
     }[Poco] public int Age {
         get;
         set;
     }
 }

This is the same approach used to add data annotations to members in your EF objects. (See http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs) Now we need a way to automatically return a JsonResult with only the properties we have given our attribute to. For this we can create an extension method:

  public static Dictionary < string, object > GetPocoDictionary(this EntityObject obj) {
     PropertyInfo[] properties = obj.GetType().GetProperties();
     var pocoMembers = properties.Where(d => d.GetCustomAttributes(typeof(PocoAttribute), true).Count() >= 1).ToArray();
     var metadataAttribute = (MetadataTypeAttribute) obj.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();
     var metaClassMembers = metadataAttribute.MetadataClassType.GetProperties().Where(d => d.GetCustomAttributes(typeof(PocoAttribute), true).Count() >= 1).ToArray();
     var combinedPoco = pocoMembers.Union(metaClassMembers);
     var allMembers = from propall in properties join combined in combinedPoco on propall.Name equals combined.Name select propall;
     var dict = new Dictionary < string,
         object > ();
     foreach(var item in allMembers) {
         dict.Add(item.Name, item.GetValue(obj, null));
     }
     return dict;
 }

This will take any EF object and return a dictionary with only the members that we have given the attribute to. Now to use it:

 return Json(Person.GetPocoDictionary(), JsonRequestBehavior.AllowGet);

That's it!

Comments

saswat: Thanx. I was waiting for this thing only. I have serched throught every where and finally i got from u. thank u so much