在动作方法中,如何将post数据绑定到动态对象

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

本文关键字:post 数据绑定 对象 动态 方法      更新时间:2023-09-26

我想这样做:

public ActionResult SaveStuff(dynamic vm) {
    StoreTheValue(vm.myvalue);
    return Content("Saved :)");
}

这不起作用,MVC似乎不想创建一个具有与请求的post数据对应的属性的动态对象。

现在我知道,正确定义视图模型的整个点是创建强类型的数据结构,并有MVC绑定数据到他们,但鉴于我张贴的数据从javascript使用ajax它不是强类型的数据,所以我没有看到,我失去了任何可维护性通过这样做,它将节省我的时间和精力创建视图模型类。

有没有人可以帮助建议我如何将post数据绑定到动态对象,可能使用自定义模型绑定器?

实现此目的的一种可能方法是使用自定义模型绑定器,假设您将Json发送到操作

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() );
            }
        }
    }

那么在你的操作中你可以告诉它,使用自定义绑定

public ActionResult SaveStuff([ModelBinder(typeof(DynamicBinder))]dynamic vm) {
    StoreTheValue(vm.myvalue);
    return Content("Saved :)");
}

然后像这样发布你的json:

{
   "myvalue":{...}
}

dynamic类型和ajax请求,你做的javascript 是不对应的

你总是可以在javascript端创建你的强类型对象属性。

无论如何,你可以这样使用FormCollection:

[HttpPost]
public ActionResult yourAction(FormCollection collection)
{
    StoreTheValue(Convert.ToString(collection["myvalue"]));
    return Content("Saved :)");
}