[英]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.这不起作用,MVC 似乎不想创建具有与请求的 post 数据相对应的属性的动态对象。
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.现在我知道正确定义的视图模型的重点是创建强类型数据结构并将 MVC 绑定数据到它们中,但是鉴于我使用 ajax 从 javascript 发布数据,它无论如何都不是强类型数据,所以我不t 看到我这样做失去了任何可维护性,这将节省我创建视图模型类的时间和精力。
Can anyone help suggest how I can bind post data to a dynamic object, posssibly using a custom model binder?任何人都可以帮助建议我如何将发布数据绑定到动态对象,可能使用自定义模型绑定器?
dynamic
type and ajax request that you do with javascript is not corresponding .你用javascript做的dynamic
类型和ajax请求不对应。
You always can create your strongly typed object properties on javascript side.您始终可以在 javascript 端创建强类型对象属性。
Anyway you can use FormCollection
like this:无论如何,您可以像这样使用FormCollection
:
[HttpPost]
public ActionResult yourAction(FormCollection collection)
{
StoreTheValue(Convert.ToString(collection["myvalue"]));
return Content("Saved :)");
}
But I think it's better to think of a strongly typed way.但我认为最好考虑一种强类型的方式。
One possible way to achieve this would be to use a custom model binder, assuming that you are posting Json to the action实现此目的的一种可能方法是使用自定义模型绑定器,假设您将 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() );
}
}
}
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 :然后像这样发布你的json:
{
"myvalue":{...}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.