首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ASP.NET复选框未设置布尔值

ASP.NET复选框未设置布尔值
EN

Stack Overflow用户
提问于 2020-04-07 12:59:25
回答 1查看 188关注 0票数 1

首先,感谢您的帮助。我是个新手。

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

查看:

代码语言:javascript
复制
<div class="checkbox">
    <label>
         <input id="lunch45" type="checkbox" value="true">45 minute lunch
    </label>
</div>

jQuery:

代码语言:javascript
复制
<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>

型号:

代码语言:javascript
复制
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; }
}

再次感谢。我知道这应该是多么简单,但什么都不起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-07 20:12:08

尝试使用1和0,阅读有关JS布尔函数here的信息

检查

代码语言:javascript
复制
alert(Boolean(Number("0")));
alert(Boolean(Number("1")));

然后

代码语言:javascript
复制
  <input id="lunch45" type="checkbox" value="0" />
  ...
  model.LongerLunch = Boolean(Number($('#lunch45').val()));

或直接使用复选框

代码语言:javascript
复制
model.LongerLunch = $('#lunch45').is(":checked");

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

代码语言:javascript
复制
<input id="lunch45" type="checkbox" value="0" >
<input id="lunchx" type="checkbox" value="1" checked>

alert($('#lunch45').is(":checked"));
alert($('#lunchx').is(":checked"));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61073099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档