0

I have an URL of API. I want to make an action in controller to get all data

BranchesController.cs:

 public Task<IEnumerable<BranchVm>> GetAllAsync()
    {
        string baseUrl = "http://api.diamond.smart-gate.net/api/Branches/GetBranches";
        var client = new HttpClient();
        var task = client.GetStringAsync(baseUrl);
        return task.ContinueWith<IEnumerable<BranchVm>>(innerTask =>
        {
            var json = innerTask.Result;
            return JsonConvert.DeserializeObject<BranchVm[]>(json);
        });
    }

Branch.js:

 columns: [
 {
    "data": 'branchArName',
    "name": "branchArName",
    "autoWidth": true,
    "orderable": true
   },
    {
   "data": 'branchEnName',
   "name": "branchEnName",
   "autoWidth": true,
   "orderable": true,
   },
 ],
   ajax: {
      url: "/Branches/GetAllAsync",
      dataSrc: ''
 }

It doesn't return any data but when I debug it , I have all data in innerTaslk.Result but var json equals null. so, I don't know why ?

7
  • This is working fine for me, how are you calling this method? Commented Dec 25, 2017 at 10:54
  • i use path of this method in js file ... when i debug i got var json = null :/ Commented Dec 25, 2017 at 10:56
  • 1
    Why not make the method properly async then? No need for the ContinueWith stuff. Commented Dec 25, 2017 at 10:57
  • So , What should i do ? Commented Dec 25, 2017 at 11:00
  • 2
    I mean something like this Commented Dec 25, 2017 at 11:01

1 Answer 1

3

You're trying to do async code without using async. That method is much simpler if you use proper async syntax. This should solve problems with how you are calling it:

public async Task<IEnumerable<BranchVm>> GetAllAsync()
//     ^^^^^
//     Make the method async
{
    string baseUrl = "http://api.diamond.smart-gate.net/api/Branches/GetBranches";
    var client = new HttpClient();
    var json = await client.GetStringAsync(baseUrl);
    //         ^^^^^
    //         await the async call instead of messing around with tasks
    return JsonConvert.DeserializeObject<BranchVm[]>(json);
}
Sign up to request clarification or add additional context in comments.

Comments

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.