0

I would like to return back from my API a list of all the products that were updated by the API. The API is called by some AngularJS code that uses a promise that returns data. In what format should I build a string of Products on the server-side that can be interpreted by Angular on the client-side?

C#

 string results = "WidgetA - $12, WidgetB - $22 - ....":
 return Request.CreateResponse<string>(HttpStatusCode.OK, results);

HTML

<div ng-repeat="model in data ">
    {{model.ProductName  + '  ' + model.ProductPrice + ' imported'  }}
</div>

Angular

.then(function (data) {
    // promise fulfilled
    if (data === '') {
        alert("No Data Returned");
    } else {
        // Data is returned
        // How to get it in model that can be iterated over
    }
}

Ideally I would like to end up with a list a Products and Prices that were updated.

1 Answer 1

2

The problem is that you're returning a string. Which is just, well, a string. But you want to return an array of something.

So return an array of something:

var results = new List<Product>
{
    new Product("WidgetA", 12.0),
    new Product("WidgetB", 22.0)
};
return Request.CreateResponse<IEnumerable<Product>>(HttpStatusCode.OK, results);

(Assuming you've created a Product class, of course. Construct that however you like.)

Then client-side:

.then(function (data) {
    // promise fulfilled
    if (data.length === 0) {
        alert("No Data Returned");
    } else {
        // "data" is an array of products here
    }
}

Structured and defined models are generally easier to work with than string blobs that would need to be parsed and interpreted anywhere you want to use them.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks David! That makes a lot of sense.Given that array returned as data how would I iterate over that in Angular in the ng-repeat?
@webworm: I'm not entirely an expert on Angular, but I suspect the view would just be binding to the model, no? I found a simple example here: jsfiddle.net/austinnoronha/RkykR Basically data is your array, just as m is an array in that example.

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.