发布子类的集合 [英] Posting a collection of subclasses

查看:145
本文介绍了发布子类的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求用户编辑报价列表的带动下,报价可以是不同类型,如:

I have a requirement for users to edit a list of quotes for a lead, the quotes can be different types such as:


  • QuoteForProductTypeA

  • QuoteForProductTypeB

所有报价类型都有一个共同的基类,如QuoteBase。

All quote types share a common base class, such as QuoteBase.

我有我的报价在前端显示的罚款,并出现过回发正确的数据。

I have my quotes displaying fine on the front end, and appear to post back the correct data too.

然而,这并不显然不知道用哪个子在服务器上,因此只要使用的基类。

However, on the server it doesn't obviously doesn't know which subclass to use, so just uses the base class.

我想我需要一些自定义模型粘结剂为的WebAPI检查隐藏字段,如ModelType其中包含集合中的对象的类型,模型绑定,然后创建该类型的新对象,并绑定属性从我的贴值到这个对象。

I think i need some kind of custom model binder for WebApi to check for a hidden field such as ModelType which contains the type of the object in the collection, the model binder then creates a new object of this type and binds the properties from my posted values to this object.

不过,我被困在这一点上如何做到这一点很少的文档/博客。

However, i am stuck at this point with very little documentation / blogs on how to do this.

我已经检查了源$ C ​​$ c代表的WebAPI,看看我是否可以延长默认的模型绑定,但任何违约密封类。

I have checked the source code for WebApi to see if i can extend a default model binder, but any defaults are sealed classes.

我只能给它的外观实现IModelBinder,我可以通过寻找一个叫ModelType值创建正确的型号,但我不知道如何填写值的休息,在我的子类,如果有在默认的模型绑定我是从我继承的只是调用基类绑定的方法。

I can only implement IModelBinder by the looks of it, i can create the correct model type by looking for a value called ModelType, but then i'm not sure how to fill the rest of the values in my subclasses, if there was a default model binder i was inheriting from i would just call the base classes bind method.

推荐答案

如果您的文章收集来自请求主体,它不会通过模型粘合剂。网页API将使用格式化反序列化的内容。

If your post collection comes from request body, it won't go through model binder. Web API will use formatter to deserialize the content.

如果你只是想支持JSON,这是相当容易的。只需添加以下code到Web API的配置:

If you just want to support json, it's quite easy. Just add following code to your web api config:

config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;

设置会让json.net在有效载荷保存类型名称,如果运行时类型的声明类型不同。当你邮寄回来,json.net将反序列化的有效载荷到您在负载指定的类型。

The setting will let json.net to save type name in the payload if the runtime type is different with the declare type. When you post it back, json.net will deserialize the payload to the type you specified in the payload.

一个样品的有效载荷是这样的:

A sample payload looks like:

{"$type":"MvcApplication2.Models.Car, MvcApplication2","SeatCount":10,"WheelCount":4,"Model":0,"Brand":null}]

这篇关于发布子类的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆