【问题标题】:ASP.NET Checkbox not setting bool valueASP.NET 复选框未设置布尔值
【发布时间】:2020-04-07 20:18:32
【问题描述】:

首先,感谢您的帮助。我很新。

这应该非常简单,但我已经花了几个小时试图弄清楚这一点。在我看来,我有一个表格。该表单正在正确填充所有内容 - 除了复选框。我在网上研究和研究并尝试了很多不同的建议。无论我尝试什么,表单都会为选中和未选中设置相同的值。

查看:

<div class="checkbox">
    <label>
         <input id="lunch45" type="checkbox" value="true">45 minute lunch
    </label>
</div>

jQuery:

<script>
    $(document).ready(function () {
        $("#Lunchsubmit-form").click(function () {
            var model = {};
            model.EmployeeID = Number($("#lunchemployeeId").val());
            model.LunchTime = Date($('#lunchtimeId').val());
            model.PositionID = Number($("#lunchposition").val());
            model.LongerLunch = Boolean($('#lunch45').val());
            console.log("model", model);
            $.ajax({
                type: "HttpPost",
                url: "/Home/CreateLunch",
                dataType: 'json',
                data: JSON.stringify(model),
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (data.success)
                        window.location.href = "/Home/Index";
                    else
                        alert("Error: Lunch not submitted");
                },
                error: function () {
                    alert("Error: Lunch not submitted");
                }
            });
        });
    });
</script>

型号:

public class Lunch
{
    public int LunchID { get; set; }
    public int EmployeeID { get; set; }
    public DateTime LunchTime { get; set; }
    public int? PositionID { get; set; }
    public bool LongerLunch { get; set; }

    public virtual Employee Employee { get; set; }
    public virtual Position Position { get; set; }
}

再次感谢。我知道这应该是多么简单,但没有任何效果。

【问题讨论】:

  • 或简单的 。然后该值可以采用您需要的任何字符串或数字。
  • 这能回答你的问题吗? Input Checkbox checked by default
  • 不幸的是它没有。我已经尝试过了...我认为代码中肯定还有其他错误。所有这些建议都返回相同的值。我将其更新为: 它双向返回 true .....我试过了将值中的 true 更改为 false - 还尝试将值留空。双向返回相同的值。
  • 尝试使用 1 和 0 ,false 不等于 'false' 检查布尔函数geeksforgeeks.org/javascript-boolean

标签: jquery asp.net-mvc checkbox


【解决方案1】:

尝试使用 1 和 0 ,了解 JS 布尔函数 here

检查

alert(Boolean(Number("0")));
alert(Boolean(Number("1")));

然后

  <input id="lunch45" type="checkbox" value="0" />
  ...
  model.LongerLunch = Boolean(Number($('#lunch45').val()));

或者直接使用复选框

model.LongerLunch = $('#lunch45').is(":checked");

或者您可能需要在获取值之前检查是否已验证

<input id="lunch45" type="checkbox" value="0" >
<input id="lunchx" type="checkbox" value="1" checked>

alert($('#lunch45').is(":checked"));
alert($('#lunchx').is(":checked"));

【讨论】:

  • 你是个天才! 和 model.LongerLunch = $('#lunch45').is(":checked");工作得很好。我确实必须将 value="0" 更改为 value="" 以使其正确保存到数据库中。但否则效果很好。谢谢!!!!
猜你喜欢
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多