BG100 BG100 - 3 months ago 18
C# Question

In an action method, how can I bind post data to a dynamic object?

I want to do this:

public ActionResult SaveStuff(dynamic vm) {

StoreTheValue(vm.myvalue);

return Content("Saved :)");
}


This doesn't work, MVC doesn't seem to want to create a dynamic object with properties that correspond to the post data of the request.

Now I know that the whole point of properly defined view models is to create strongly typed data structures and have MVC bind data into them, but given that I'm posting data from javascript using ajax it's not strongly typed data anyway, so I don't see that I'm loosing any maintainability by doing this, and it will save me time and effort creating view model classes.

Can anyone help suggest how I can bind post data to a dynamic object, posssibly using a custom model binder?

Answer

One possible way to achieve this would be to use a custom model binder, assuming that you are posting Json to the action

public class DynamicBinder : IModelBinder
    {
        public object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
        {
            using( var streamReader = new StreamReader( controllerContext.HttpContext.Request.InputStream ) )
            {
                return JsonConvert.DeserializeObject< dynamic >( streamReader.ReadToEnd() );
            }
        }
    }

then in your action you can tell it, to use the custom binder

public ActionResult SaveStuff([ModelBinder(typeof(DynamicBinder))]dynamic vm) {

    StoreTheValue(vm.myvalue);

    return Content("Saved :)");
}

then post your json as such :

{
   "myvalue":{...}
}
Comments