Search code examples
c#c#-4.0asp.net-mvc-3namevaluecollection

How do I update an objects parameters from a NameValueCollection (or similar)?


I am trying to update public parameters of a known type MyClass from a NameValueCollection (see code below). This is possible in MVC3, the Controller class has an UpdateModel method which does exactly this with the Request.Params. I would like to do this outside of the Controller though.

Any thoughts?

public class MyClass
{
    public string MyParam { get; set; }
}

...

var values = new NameValueCollection() { { "MyParam", "any string value for my param" } };
var myInstance = new MyClass();
Update(myInstance, values);

Cheers, T


Solution

  • You should use reflection to perform this task:

    This code is provided without proper validation, and it should be put into a method.

    var type = myInstance.GetType();
    foreach(var keyValue in values)
    {
       type.InvokeMember(keyValue.Key,BindingFlags.SetProperty,null,myInstance,  new object[]{keyValue.Value});    
    
    }
    

    There could be an error in this code, but even if it's the case, the general idea is here. 2 remarks: This code will fail miserably if the property doesn't exist on MyClass, or if the property type cannot be assigned from a string. It would therefore require proper validation (I know, I am repeating myself ).

    You could use expression tree to perform the job too, particularly if you are setting a lot of values on the same known type, as expression trees can be compiled.