2017-08-31 60 views
2

我有類似這樣的.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中實現同樣的功能嗎?

回答

0

在您的視圖中,您首先發送一個SupplierViewModel,然後在您希望供應商對象的表單的POST上發送。

你可以做兩件事情之一:

一)更改POST模型SupplierViewModel

B)更改初始模型供應商,並把額外的屬性,並列出了ViewBag

+0

這打破了ViewModel的全部目的,而且PrimaryContact對象也不會以下面的形式構建:Supplier.PrimaryContact.Name,但我必須重新格式化它,正如我現在所做的那樣。我想實現的是這個公共'ActionResult SuppliersAddOrEdit(供應商供應商,int idSupplier = 0)',因爲它的工作原理與我想要的完全一樣,所以必須有一種方法可以在Web API控制器中實現相同的結果 –