Thursday, July 10, 2014

C# - Assign one class properties to another class properties using reflection

Following code helpful to assign properties of one class to another class object

 public static void MapProperties<T1, T2>(T1 destinationClass, T2 sourceClass)
        {
            if (destinationClass != null & sourceClass != null)
            {
                Type destinationType = destinationClass.GetType();
                Type sourceType = sourceClass.GetType();


                foreach (PropertyInfo sourceProperty in
                    sourceType.GetProperties())
                {
                    if (sourceProperty.CanRead)
                    {
                        string propertyName = sourceProperty.Name;
                        Type propertyType = sourceProperty.PropertyType;

                        PropertyInfo destinationProperty =
                            destinationType.GetProperty(propertyName);
                        if (destinationProperty != null)
                        {
                            Type toPropertyType = destinationProperty.PropertyType;

                           if (toPropertyType == propertyType && destinationProperty.CanWrite)
                            {
                             object sourceValue = sourceProperty.GetValue(sourceClass, null);
                            destinationProperty.SetValue(destinationClass, sourceValue, null);
                            }
                        }
                    }
                }
            }

        }

Tuesday, July 8, 2014

MVC Razor - DropdownListFor with index list binding

In MVC Razor, sometimes we feel selected value not reflect when we use indexed selected

Ex:    @Html.DropDownListFor(m => m.EmployeeDetails[0].StateId,
                        Model.StateList,
                        new { @class = "classname" })

in the above example state will not selected as it taken from employeeDetail list.

Change the code as below and it will work

  @Html.DropDownListFor(m => m.EmployeeDetails[0].StateId,
                        new SelectList(Model.StateList, "Value", "Text", Model. EmployeeDetails[0].StateId),
                        new { @class = "classname" })