【问题标题】:Checkbox value always 0 after insert into database插入数据库后复选框值始终为 0
【发布时间】:2017-11-10 14:53:00
【问题描述】:

我正在使用Asp.Net MVC 建立一个网站。我已成功将表单数据插入数据库。但是,我的复选框有问题,即使选中了复选框,我的数据库中的值也始终为 0。

@using (Html.BeginForm())
{
    <div class="modal-body">
        <div class="form-group">
            <label for="username" class="col-form-label">Name:</label>
            <input type="text" class="form-control" **id="username" name="username" **>
        </div>
        <div class="row">
            <div class="form-group">
                <div class="col-md-6">
                    <input type="checkbox" **id="user_privilage" name="user_privilage" **>
                    <label for="user" class="col-form-label">User</label>
                </div>
            </div>
        </div>
    </div> 
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Add</button>
    </div>
}

这是控制器中的代码:

[HttpPost]
public ActionResult UserMaintenance(User collection)
{
    try
    {
        List<object> lst = new List<object>();
        lst.Add(collection.username);
        lst.Add(collection.user_privilage);
        object[] allitems = lst.ToArray();
        int output = db.Database.ExecuteSqlCommand("insert into DATABASE(username,user_privilage) values (@p0,@p1)", allitems);
        if(output>0)
        {
            ViewBag.msg = "User has been added";
        }
        return View();
        //return RedirectToAction("UserMaintenance");
    }
    catch {
        return View();
    }
}

有人知道发生了什么吗?

【问题讨论】:

  • 始终使用视图模型
  • 你没有给复选框一个值(所以如果它被选中,它会发回"on")。使用具有bool 属性的视图模型,并使用@Html.CheckBoxFor(m =&gt; m.yourProperty) 强绑定到您的模型,所有控件都同上

标签: c# asp.net-mvc razor checkbox


【解决方案1】:

您正在使用纯 html 标记复选框,因为您需要将复选框的值设置为 true。

型号

查看

运行时视图

POST 动作方法

我们已经检查了复选框并提交了表单,我们必须在 user_privilage 模型属性中获得值 true。

同样,如果我们取消选中复选框,那么我们将得到错误值。

【讨论】:

    猜你喜欢
    • 2015-07-19
    • 1970-01-01
    • 2019-01-04
    • 2010-09-19
    • 2016-11-22
    相关资源
    最近更新 更多