Home > Back-end >  How to update data through Api in Xamarin
How to update data through Api in Xamarin

Time:09-17

I do the update command through the API. Everything seems fine. However, the data is not up to date. When I debug there is no error.

    public async Task UpdateViewRatingStore(bool value)
    {
        var url = baseUrl   userget;
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", mytokenlogin);
        string jsonStr = await client.GetStringAsync(url);

        var res = JsonConvert.DeserializeObject<Customer>(jsonStr);

        var checkunredrating = res.RatingStores;

        if (checkunredrating != null)
        {
            foreach (var r in checkunredrating)
            {
                r.ID = r.ID;
                r.StoreID = r.StoreID;
                r.RatingStores = r.RatingStores;
                r.CommentStore = r.CommentStore;
                r.UserRating = r.UserRating;
                r.CreateDay = r.CreateDay;
                r.Display = r.Display;
                r.ViewStorer = value;

                var urlput = baseUrlStoreRating   r.ID;
                var stringContent = new StringContent(JsonConvert.SerializeObject(res.RatingStores), Encoding.UTF8, "application/json");
                await client.PutAsync(urlput, stringContent);
            }
        }
    }

enter image description here

However when I check in the database it is still not updated. I tested it manually on swagger and Posman was fine. Where did I go wrong? Ask for help. Thank you

CodePudding user response:

you are trying to update a single object, but passing the entire collection every time

instead, try this

foreach (var r in checkunredrating)
{
    // you only need to update the changed values
    r.ViewStorer = value;

    var urlput = baseUrlStoreRating   r.ID;

    // only send the current object you are updating
    var stringContent = new StringContent(JsonConvert.SerializeObject(r), Encoding.UTF8, "application/json");
    await client.PutAsync(urlput, stringContent);
}
  • Related