Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Can't bind multiple parameter to the request's content." in web api and angularJs

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");
})
like image 230
safeena rasak Avatar asked Jun 22 '17 05:06

safeena rasak


3 Answers

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
}
like image 174
Lukas Kolletzki Avatar answered Sep 28 '22 23:09

Lukas Kolletzki


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)
like image 38
Marcus Höglund Avatar answered Sep 29 '22 00:09

Marcus Höglund


[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

like image 40
safeena rasak Avatar answered Sep 29 '22 00:09

safeena rasak