0

I'm trying to pass a object which has multiple objects inside it as below

[Object, Object, Object, Object]
0
:
Object
ProductID
:
"50"
__proto__
:
Object
1
:
Object
BrandID
:
24
__proto__
:
Object
2
:
Object
BrandID
:
26
__proto__
:
Object
3
:
Object
BrandID
:
20
__proto__
:
Object

One of these objects has different key value pair than the others. How can I get capture this data from a Web Api controller. How should I modify my Model in the Web Api project.

2
  • 1
    It would be better to show json here, because showed data structure is unclear. Commented Jun 1, 2016 at 10:58
  • the json should be object=[{ProductID:"50"},{BrandID:"24"},{BrandID:"26"},{BrandID:"20"}] Commented Jun 1, 2016 at 11:01

2 Answers 2

1

It seems to me that the array you are trying to send to Web API contains different objects with different schemas. This approach is certainly error prone, and will not allow you to use ModelBinding properly.

Why don't you change the format of your object to something like this?

$scope.myObject = {
    ProductID: 50,
    BrandIDs: [24, 26, 20]
};

Using this kind of object you will be able to bind it to a strongly typed model in Web API.

public class MyModel {
    public int ProductID { get; set; }
    public List<int> BrandIDs { get; set; }
}

public IHttpActionResult Post(MyModel model) {
    var productId = model.ProductID;
    foreach(var brandId in model.BrandIDs) {
        DoSomething(brandId);
    }
    return Ok();    
}
Sign up to request clarification or add additional context in comments.

2 Comments

I was killing my self to get a scope object like that to pass. But couldn't do that
May you explain why?
1

You just need to create a class model that corresponds to you JSON and Web Api will automatically bind it. It seems that what you are passing is an array, so you can do something like that:

public void Execute(Model[] input)
{

}

....

public class Model
{
    public int? ProductId {get;set;}
    public int? BrandId {get;set;}
}

Or if you want one object with an array inside you can pass a class like that

public class ProductsContainer
{
     public Product[] Products {get;set;}
}

4 Comments

Since I'm passing multiple BrandIDs would this model be OK to use. ?
I am not quite sure what you mean by multiple BrandIds, if you mean multiple objects each of them containing a BrandId, then yes it will be totally fine.
Thank you so much.
You are welcome, please don't forget to accept the answer if you liked it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.