Tarek J.
Tarek J.

Reputation: 21

C# DefaultModelBinder does not bind property of type "dynamic"

I have been trying to figure this one out for the past 2 days...
My main model contains a property of type "dynamic" and looks like this:

public class WGTTestModel
{
    private dynamic _oProp3 = null;

    public WGTTestModel()
    {
    }

    public int Prop1 { get; set; }
    private string Prop2 = null;

    public dynamic Prop3
    {
        get
        {
            if (_oProp3 == null)
            {
                // depending on other factors, this could return a different model
                _oProp3 = new SubModel1();
            }

            return _oProp3 ;
        }
        set
        {
            _oProp3 = value;
        }
    }
}  

SubModel1 looks like this:

public class SubModel1
{
    public SubModel1()
    {
    }

    public int Prop1 { get; set; }
    public string Prop2 { get; set; }
}  

The property "WGTTestModel.Prop3" is passed through to a partial view like so:

@Html.Partial("~/MVCFrontEnd/Widgets/TESTING/Views/_PartialView.cshtml", (object)Model.Prop3)  

Note that I had to add the cast to (object) as it was not allowing me to pass along a "dynamic" type.

Problem: Values that I set on properties "SubModel1.Prop1" & "SubModel1.Prop2" in my partial view do not bind when posting the form.

The other test I made is by changing the type of "Prop3" from "dynamic" to "SubModel1" in my "WGTTestModel". I was then able to remove the cast to object when passing the model over to the partial view. This time everything works as expected and values bind correctly.

Is the DefaultModelBinder unable to bind "dynamic" type properties? If so, is there any possible workaround?

Any help will be appreciated!

Upvotes: 0

Views: 224

Answers (0)

Related Questions