Le Dinh Nhat Khanh Le Dinh Nhat Khanh - 3 months ago 12
Ajax Question

Asp.net core bind data to button

I'm learning ASP.NET Core MVC.
I have this model:

public class Todo
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[MaxLength(4096)]
public string Content { get; set; }
public bool isCompleted { get; set; } = false;
public DateTime DateCreated { get; set; } = DateTime.UtcNow;
public string UserName { get; set; }
}


And I want to bind the
isCompleted
to the button like: when I click that button, it's value will be changed. Currently I'm using Ajax:

CompleteTodo = function (id, isCompleted) {
if (isCompleted === true) {
var data = "{\n \"isCompleted\": false,\n}"
} else {
var data = "{\n \"isCompleted\": true,\n}"
}
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:3000/api/todos/"+id,
"method": "PUT",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache",
},
"data": data
}

$.ajax(settings).done(function (response) {
console.log(response);
});
}


The problem is, I can't change the button's class after the call, my button tag:

<button id="ButtonComplete" href="#" onclick='CompleteTodo(@item.Id,@item.isCompleted.ToString().ToLower())' class="waves-effect waves-light @(item.isCompleted?"blue":"green") btn">@if (!item.isCompleted)
{ <i class="material-icons">done</i>}
else
{ <i class="material-icons">clear</i> }</button>


So how can I do that? Thank you.

Answer

Since you use server side binding, button class does not change without refreshing page. Refresh the page when ajax completed:

$.ajax(settings).done(function (response) {
    console.log(response);
    location.reload(false);
});

Or change class(add/remove) on the client side with javascript.

ps: Make sure after ajax call item.isCompleted changes as expected.