问题描述:在前台,把一个bool量绑定给一个checkbox,当后台的值变更后,前台的checkbox状态没有同步更新,而只是单纯得保留提交表单时得状态。

重现步骤:

1. 利用VS创建一个asp.net core 6.0得项目。

controller:

复制代码
        public IActionResult TestArrayData(RedcodeModel model)
        {
            if (model == null)
                model = new();

            if (model.ConditionType > 0)
                model.IsSkipLinked = true;
            else
                model.IsSkipLinked = false;

            return View("TestArrayData", model);
        }
复制代码

view:

复制代码
@model RedcodeModel
<div>
    <form asp-controller="Configuration" asp-action="TestArrayData" method="post">
        <input type="text" asp-for="ConditionType" value="@Model.ConditionType" />
        <input type="checkbox" asp-for="IsSkipLinked" />
        <label>@Model.IsSkipLinked</label>
        <div style="padding-top:10px">
            <button type="submit" class="btn btn-lg btn-primary" style="width:250px">保存</button>
        </div>
    </form>
</div>
复制代码

model:

    public class RedcodeModel
    {
        public int ConditionType { get; set; } = 1;

        public bool IsSkipLinked { get; set; } = false;
    }

测试结果:无论在文本框里输入1 还是 0, checkbox始终保持选中状态,当手动取消选中状态后,无论文本框里输入1 还是 0,checkbox始终保持未选中状态。

workaround:在提交时不提交checkbox,手动的把checkbox的name拿掉。

复制代码
@model RedcodeModel
<div>
    <form id="linkform" asp-controller="Configuration" asp-action="TestArrayData" method="post">
        <input type="text" asp-for="ConditionType" value="@Model.ConditionType" />
        <input type="checkbox" asp-for="IsSkipLinked" />
        <label>@Model.IsSkipLinked</label>
        <div style="padding-top:10px">
            <button type="button" class="btn btn-lg btn-primary" style="width:250px" onclick="queryLink()">保存</button>
        </div>
    </form>
</div>
<script>

    function queryLink() {
        $('input[name="IsSkipLinked"]').removeAttr('name');
        $('#linkform').submit();
    }
</script>
复制代码

终极解决方案待查。