2015-04-29 109 views
3

我有两种不同的模型需要传递给web api。这两个样品模型如下 将POST参数传递给WEB API2

public class Authetication 
{ 
    public string appID { get; set; } 
} 

public class patientRequest 
{ 
    public string str1 { get; set; } 
} 

所以要得到这个工作,我创建了一个模型,第三是如下。

public class patientMaster 
{ 
    patientRequest patientRequest; 
    Authetication Authetication; 
} 

和通过我已经建立以下的jquery代码数据

var patientMaster = { 
    patientRequest : { "str1" : "John" },          
    Authetication : { "appID" : "Rick" } 
} 


$.ajax({ 
      url: "http://localhost:50112/api/Patient/PostTestNew", 
      type: "POST", 
      data: {"": patientMaster} 
     }); 

和捕获此我已经建立以下在控制器方法

[HttpPost] 
public string PostTestNew(patientMaster patientMaster) 
{ 
    return " .. con .. "; 
} 

我的问题是

每当测试我得到patientMaster对象,但我没有得到任何数据Authetication对象也不patientRequest对象

我也试图通过的contentType:jQuery的JSON,但它不工作

能有人帮我在这?

+0

尝试使用在你的'data'属性在_exact_同名你的jQuery函数作为你的ActionResult。在这种情况下:'data:{patientMaster:patientMaster}'。 –

+0

尝试过,但效果相同...得到patientMaster对象,但我没有得到任何数据认证对象,也没有patientRequest对象 – Dhaval

+0

如果你添加'dataType:“json”,“你的ajax调用? –

回答

6

你非常接近。我添加了FromBody属性并指定了内容类型。我还会将patientMaster对象中的属性公开访问。

patientMaster对象:

public class patientMaster 
{ 
    public patientRequest patientRequest { get; set;} 
    public Authetication Authetication { get; set;} 
} 

API控制器:

[HttpPost] 
public string PostTestNew([FromBody]PatientMaster patientMaster) 
{ 
    return "Hello from API"; 
} 

jQuery代码:

var patientRequest = { "str1": "John" }; 
var authentication = { "appID": "Rick" }; 
var patientMaster = { 
     "PatientRequest": patientRequest, 
     "Authentication": authentication 
}; 

$.ajax({ 
     url: "http://localhost:50112/api/Patient/PostTestNew", 
     type: "POST", 
     data: JSON.stringify(patientMaster), 
     dataType: "json", 
     contentType: "application/json", 
     traditional: true 
});