When Multiple parameters pass in WebApi
it results as an exception "Can't bind multiple parameter to the request's content."
.Have any solution for following code
public class A1
{
public int id {get;set;}
public string name {get;set;}
}
public class A2
{
public int id2 {get;set;}
public string name2 {get;set;}
}
[Route("Save")]
[HttpPost]
public string Save([FromBody]A1 Emp, [FromBody]List<A2> EmpMarks)
{
}
JS file
$http({
method: "post",
url: "/api/Employee/Save",
data: JSON.stringify({
Emp: $scope.Emp,
EmpMarks: $scope.EmpMarks
})
}).then(function (response) {
}, function () {
alert("Error Occur");
})
You might want to use a model which contains your data:
public class A1
{
public int id { get; set; }
public string name { get; set; }
}
public class A2
{
public int id2 { get; set; }
public string name2 { get; set; }
}
public class AModel
{
public A1 Emp { get; set; }
public A2 EmpMarks { get; set; }
}
[Route("Save")]
[HttpPost]
public string Save(AModel aData)
{
// ... your logic here
}
The issue occours because you are declaring the [FromBody]
attribute twice. As per design, http POST does only have one body and the [FromBody]
will try to read all content in the body and parse it to your specified object.
To solve this issue you need to create an object which matches your client object which is being attach to the request body.
public class RequestModel
{
public A1 Emp {get;set;}
public List<A2> EmpMarks {get;set;}
}
Then fetch that from the request body in your post method
[Route("Save")]
[HttpPost]
public string Save([FromBody]RequestModel Emps)
[Route("Save")]
[HttpPost]
public string Save(JObject EmpData)
{
dynamic json = EmpData;
A1 Emp=json.Emp.ToObject<A1>();
List<A2> EmpMarks=json.ToObject<List<A2>>();
}
It is an another option.It is work for me
If you want to pass multiple parameters to a POST call, you can simply do as below and add as many to match the service.
var data = new FormData();
data.append('Emp', $scope.Emp);
data.append('EmpMarks', $scope.EmpMarks);
$http.post('/api/Employee/Save', **data**, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
}).success(function(resp) { });