user1110790
user1110790

Reputation: 787

How Do i pass form values from a Dictionary <String, String> to an Object in C#

I am getting Values from a form in a Dictionary. Key equals field on the page and value is what the user has supplied .Is there a better way to pass the values to an object as below :I am new to this so will appreciate your help . Thanks for your help
I get the values using the following call :

public async void PostFormData()

Now I am trying to pass the values from the dictionary to an Object as below . The method below is very elementary and I am looking to make this more dynamic .

public static void ConverttoObject()
                {
                    Dictionary<string, string> test = new Dictionary<string, string>();

                    test.Add("Name", "Daniel");
                    test.Add("LastName", "Wong");
                    test.Add("Zip", "60004");
                    test.Add("City", "New York");


                    var abc = new FormInfo();

                    foreach (var key in test.Keys)
                    {
                        foreach (var val in test.Values)
                        {
                            if (key.Equals("Name"))
                                abc.Name = val;
                            else if (key.Equals("LastName"))
                                abc.City = val;
                            else if (key.Equals("Zip"))
                                abc.Zip = val;
                            else if (key.Equals("City"))
                                abc.City = val;

                        }
                    }
                }
            }

            public class FormInfo
            {
                public string Name { get; set; }
                public string LastName { get; set; }
                public string Zip { get; set; }
                public string City { get; set; }

            }

Upvotes: 1

Views: 1090

Answers (2)

Vladislav Karamfilov
Vladislav Karamfilov

Reputation: 471

You could make your own extension method to convert a dictionary to an object like this one:

public static class IDictionaryExtensions
{
    public static T ToObject<T>(this IDictionary<string, object> source)
        where T : class, new()
    {
        T someObject = new T();
        Type someObjectType = someObject.GetType();

        foreach (KeyValuePair<string, object> item in source)
        {
            someObjectType.GetProperty(item.Key).SetValue(someObject, item.Value, null);
        }

        return someObject;
    }
}

Solution approach here.

Upvotes: 2

Buzinas
Buzinas

Reputation: 11725

Couldn't you do:

abc.Name = test["Name"];
abc.LastName = test["LastName"];
abc.Zip = test["Zip"];
abc.City = test["City"];

Upvotes: 0

Related Questions