的.NET Web API模型绑定前缀属性
问题描述:
我有类似这样的.NET Web API模型绑定前缀属性
public class SupplierViewModel
{
public Supplier Supplier { get; set; }
//Select Lists and other non model properties
}
而且两款车型
public class Supplier
{
public string Name { get; set; }
public Contact PrimaryContact { get; set; }
public List<Contact> SecondaryContacts { get; set; }
}
public class Contact
{
public string Name { get; set; }
}
但在我的视场得到与类名前缀视图模型和模型所以当我将它发送到Web API控制器时,它的格式如下
{
Supplier.Name: "test",
Supplier.PrimaryContact.Name: "test",
Supplier.SecondaryContacts: [
{ Name: "test" }
]
}
当我将它发送到我的控制器
[System.Web.Http.Route("Suppliers/{idSupplier?}")]
public HttpResponseMessage SuppliersAddOrEdit(Supplier Supplier, int idSupplier = 0)
这显然不反序列化,因为前缀的,我目前格式化之前我发这样的
{
Name: "test",
PrimaryContact: {Name: "test"},
SecondaryContacts: [
{
Name: "test"
}
]
}
然后将其绑定确定的请求,但我敢肯定,当我将数据发送到的ActionController它知道,即使没有指定绑定[(前缀)]为例如
PrimaryContact.Name:“测试”
会进入PrimaryContact类。如何在Web API控制器中实现相同的结果?
编辑:基于乔恩Susiak的答案,我想进一步澄清
相反,如果我使用一个控制器,而不是ApiController我的模式,因为它是将绑定就好用前缀发送的JSON数据,是有一种方法可以在ApiController中实现同样的功能吗?
答
在您的视图中,您首先发送一个SupplierViewModel,然后在您希望供应商对象的表单的POST上发送。
你可以做两件事情之一:
一)更改POST模型SupplierViewModel
B)更改初始模型供应商,并把额外的属性,并列出了ViewBag
这打破了ViewModel的全部目的,而且PrimaryContact对象也不会以下面的形式构建:Supplier.PrimaryContact.Name,但我必须重新格式化它,正如我现在所做的那样。我想实现的是这个公共'ActionResult SuppliersAddOrEdit(供应商供应商,int idSupplier = 0)',因为它的工作原理与我想要的完全一样,所以必须有一种方法可以在Web API控制器中实现相同的结果 –