Tuesday, May 26, 2015

Tip : How to copy the data between two object.

 

       Actually we may come across the scenario that we need to copy the properties form View model object to actual model object .

       Instead of coping each property from source to target , Consider serialization to copy the data from source to target.

       Serialize the source object into JSON string and Desterilize the JSON to target object.

       Example:

1.         var serilize = new JavaScriptSerializer();

    

      public class SourceModel

      {

        public int id { get; set; }

        public System.DateTime start_date { get; set; }

       public System.DateTime end_date { get; set; }

      }

     

2.       SourceModel sourceobj =  new SourceModel();

 

     public class TargetModel

    {

        public int id { get; set; }

        public System.DateTime start_date { get; set; }

       public System.DateTime end_date { get; set; }

         .

         .

         .  

    }

3.       var json = serilize.Serialize(sourceobj);

4.       var targetModel =  serilize.Deserialize<SessionViewModel>(json);

 

                  NameSpace:  System.Web.Script.Serialization

No comments:

Post a Comment