Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dynamic objects with ASP.NET MVC model binding

In an ASP.NET MVC3 application, if I wanted to model bind my form post data to an ExpandoObject (or my own object derived from DynamicObject where I implement my own Try... members) would I need to write my own custom model binder?

If I do:

public ActionResult Save(ExpandoObject form)
{
    ....
}

The value of form is null.

Or if I have:

public class MyDynamicThing : DynamicObject
{
    public int Id { get; set; }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        // Set breakpoint here but doesn't get hit when model binding
        return base.TrySetMember(binder, value);
    }
}

...and in my controller:

public ActionResult Save(MyDynamicThing form)
{
    ....
}

In the above example Id is set to the value from the form. However if I set a breakpoint in TrySetMember this doesn't get hit.

Are there any magical incantations I can invoke to coerce the built-in model binder to work with ExpandoObjects or my own classes derived from DynamicObject?

I could resort to picking up the raw form post collection but I have to serialise this data to JSON which would mean an extra and untidy step to harvest those values.

like image 731
Kev Avatar asked Oct 08 '22 13:10

Kev


1 Answers

No, this is not possible with the built-in model binder. You could of course write a custom model binder. The only property that the built-in model binder is capable of binding is the one that it seems from the MyDynamicThing type and that's why it can only set the Id property. It has no knowledge of other properties.

like image 116
Darin Dimitrov Avatar answered Oct 12 '22 00:10

Darin Dimitrov