Passing POST parameter to WEB API2

I have two different models that need to be passed to the web api. these two sampling models follow

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

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

      

so to get it working I created a third model which is below.

 
 public class patientMaster
 {
     patientRequest patientRequest;
     Authetication Authetication;
 }

      

and pass the data I created after the 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 created the following method in my controller

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

      

My problem

when testing i get object patientMaster

but i dont get any Authetication

object and patientRequest

object data

I also tried to pass contenttype: json to jquery but it doesn't work

can someone help me on this?

+3


source to share


1 answer


You were pretty close. I added a FromBody attribute and set the content type. I would also make the properties in your object patientMaster

public.

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

      

+6


source







All Articles