5

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.

3 Answers 3

2

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.

1

Try this:

public class ExpandoObjectBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException("bindingContext");

        IDictionary<string, object> model = new ExpandoObject();

        string modelName = bindingContext.ModelName;
        var form = controllerContext.HttpContext.Request.Unvalidated.Form;
        var keys = form.AllKeys.Where(k => k.StartsWith(modelName + "."));
        Debug.Write("ExpandoObjectBinder keys count is " + keys.Count());
        foreach (var key in keys)
        {
            var propName = key.Replace(model + ".", "");
            model.Add(propName, form[key]);
        }
        if (model.Count == 0)
            throw new Exception("Data is empty.");
        return model;
    }
}

Register the binder mvc initialization :

ModelBinders.Binders.Add(typeof(ExpandoObject), new ExpandoObjectBinder());

1

Type support added (int, byte, long, decimal, string, array and subobjects):

public class ExpandoObjectBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException("bindingContext");

        string modelName = bindingContext.ModelName;
        var form = controllerContext.HttpContext.Request.Unvalidated.Form;
        var model = ParseProperties(modelName, form);
        return model;
    }
    public object ParseProperties(string modelName, NameValueCollection form)
    {
        var keys = form.AllKeys.Where(k => k.StartsWith(modelName + "."));
        Debug.WriteLine("ExpandoObjectBinder keys count is " + keys.Count() + " for " + modelName);
        IDictionary<string, object> model = new ExpandoObject();
        List<string> subModelNames = new List<string>();
        List<string> arrModelNames = new List<string>();
        //ModelName: Dialog.Attributes[0].Options
        foreach (var key in keys)
        {
            //Dialog.Attributes[0].Options.Byte
            //Dialog.Attributes[0].Options.Inner.Byte
            //Dialog.Attributes[0].Options.Inner.Integer
            //Dialog.Attributes[0].Options.SimpleArray[0]
            //Dialog.Attributes[0].Options.SimpleArray[1]
            var propName = key.Replace(modelName + ".", "");
            //Byte
            //Inner.Byte
            //Inner.Integer
            //SimpleArray[0]
            //SimpleArray[1]
            if (!(propName.Contains('[') || propName.Contains('.')))
            {
                model.Add(propName, GetValue(form, key));
            }
            //array (can allow sub objects)
            if (propName.Contains('['))
            {
                var names = propName.Split('[');
                var arrModelName = names[0];
                if (!arrModelNames.Contains(arrModelName))
                    arrModelNames.Add(arrModelName);
            }
            //not array but can has sub objects
            if (!propName.Contains('[') && propName.Contains('.'))
            {
                var names = propName.Split('.');
                var subModelName = names[0];
                if (!subModelNames.Contains(subModelName))
                    subModelNames.Add(subModelName);
            }
        }

        foreach (var subModelName in subModelNames)
        {
            var key = modelName + "." + subModelName;
            object val = form[key];
            val = ParseProperties(key, form);
            model.Add(subModelName, val);
        }

        foreach (var arrModelName in arrModelNames)
        {
            //Dialog.Attributes[0].Options.SimpleArray[
            var key = modelName + "." + arrModelName + "[";
            var arrKeys = form.AllKeys.Where(k => k.StartsWith(key));
            var isComplexArray = false;
            int length = 0;
            foreach (var arrKey in arrKeys)
            {
                var aKey = arrKey.Replace(key, "");
                if (aKey.Contains("."))
                    isComplexArray = true;
                var parsed = aKey.Split(']');
                var num = int.Parse(parsed[0]);
                if (num > length)
                    length = num;
            }
            List<object> vals = new List<object>();
            if (isComplexArray)
            {
                for (int i = 0; i < length + 1; i++)
                {
                    var arrKey = key + i + "]";
                    object val = ParseProperties(arrKey, form);
                    vals.Add(val);
                }
            }
            else
            {
                for (int i = 0; i < length + 1; i++)
                {
                    var arrKey = key + i + "]";
                    vals.Add(GetValue(form, arrKey));
                }
            }
            model.Add(arrModelName, vals);
        }
        return model;
    }

    object GetValue(NameValueCollection form, string key)
    {
        object val = form[key];
        if (decimal.TryParse(form[key], out decimal decimalVal))
            val = decimalVal;
        if (long.TryParse(form[key], out long longVal))
            val = longVal;
        if (int.TryParse(form[key], out int intVal))
            val = intVal;
        if (byte.TryParse(form[key], out byte byteVal))
            val = byteVal;
        if (bool.TryParse(form[key], out bool boolVal))
            val = boolVal;
        return val;
    }
}
1
  • Heh it's so long ago I can't remember what I needed this for. I've a feeling I did actually write my own custom model binder. Thanks for the answers though. When I get some free time I'll have a play.
    – Kev
    Commented Jan 10, 2019 at 16:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.