Dhaval
Dhaval

Reputation: 2861

Passing POST parameter to WEB API2

I have two different model need to be passed to web api. those two sample model are as follow

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

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

so to get work this i have created a 3rd model which is as below.

 public class patientMaster
 {
     patientRequest patientRequest;
     Authetication Authetication;
 }

and to pass the data i have created following jquery code

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


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

and to catch this i have created following method in controller

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

My Problem is

whenever testing i am getting patientMaster object but i am not getting any data Authetication object nor patientRequest object

I also tried to pass contenttype:json in jquery but it does not work

can some one help me on this?

Upvotes: 3

Views: 9465

Answers (1)

Benjamin
Benjamin

Reputation: 2103

You were pretty close. I added a FromBody attribute and specified the content type. I'd also make the properties in your patientMaster object publicly accessible.

patientMaster object:

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

API Controller:

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

jQuery code:

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
});

Upvotes: 6

Related Questions