jquery - Asp.net core 将数据绑定(bind)到按钮

标签 jquery ajax model asp.net-core asp.net-core-mvc

我正在学习 ASP.NET Core MVC。 我有这个模型:

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; }
}

我想将 isCompleted 绑定(bind)到按钮,如下所示:当我单击该按钮时,它的值将会更改。目前我正在使用 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);
    });
}

问题是,我无法在调用后更改按钮的类,我的按钮标签:

<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>

那么我该怎么做呢?谢谢。

最佳答案

由于您使用服务器端绑定(bind),因此按钮类在不刷新页面的情况下不会更改。 ajax完成后刷新页面:

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

或者使用 javascript 在客户端更改类(添加/删除)。

ps:确保ajax调用后item.isCompleted按预期更改。

关于jquery - Asp.net core 将数据绑定(bind)到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39158891/

相关文章:

Jquery Accordion 菜单主动打开

Django写入数据库,IntegrityError

jquery - 如何减少网站加载时间

jquery - 在 jQuery 中选择子元素第一次出现的最合适方法

javascript - 如果我克隆一个元素,当我自定义(css)该元素时,如何自定义克隆的元素?

javascript - Firefox 中的 Ajax 添加面板内容 JavaScript

javascript - 等待ajax .html成功加载对象

javascript - Ajax 中的多个成功函数

mysql - Django 数据库模型 "unique_together"不工作?

具有 2 个字段的 Django 自定义字段