首页 > 解决方案 > 为什么我的复选框没有将它们的值传递给 ASP.NET Core 中的控制器?

问题描述

我觉得这可能是一个简单的解决方法,但我似乎无法绕过它。我有一个 ASP.NET Core Web 应用程序,我正在使用 ajax 表单将数据提交到我的控制器进行处理。我遇到的问题是我的复选框总是以“假”的形式传入,即使它们可能被选中。

我搜索了一些答案,但我尝试过的都没有奏效。checked使用属性,确保名称正确等事情。

谁能解释为什么在将表单提交给控制器时忽略这些值以及如何修复它?

形式

<form asp-action="CreateCustomView" asp-controller="Data"
        data-ajax="true"
        data-ajax-method="POST">
        <div class="row">
            <div class="col">
                <div class="custom-control custom-checkbox">                            
                    <input type="checkbox" class="custom-control-input" id="ColName" name="ColName" checked>
                    <label class="custom-control-label" for="ColName">Name</label>
                </div>
            </div>

            <button type="reset">Reset</button>
            <button type="submit">Save changes</button>
</form>

模型

namespace MyProject.Data
{
    public class GridView : BaseEntity
    {
        public string Name { get; set; }               
        public bool ColName { get; set; }
    }
}

数据控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MyProject.Data;
using Microsoft.AspNetCore.Mvc;

namespace MyProject.UI.Controllers
{
    public class DataController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult CreateCustomView(GridView data)
        {
            //This method is incomplete, there is a break at the ActionResult to see what values are passed into `data`.  In production, the values would be handled and the changes would be saved.
            return View();
        }
    }
}

我在方法上有一个断点CreateCustomView来查看传递了哪些值,无论我检查什么复选框,它们总是以false.

任何人都可以帮助解决这个相当奇怪的问题吗?

更新

根据@Reyan-Chougle 提供的答案,如果您使用的是 CORE,则需要提供如下输入:

<input asp-for="@Model.ColType" type="checkbox" />

呈现页面时,控件会自动获得一个隐藏字段。以下是上述控件的 HTML 呈现的内容:

<input type="checkbox" class="custom-control-input" id="ColType" value="true" data-val="true" data-val-required="The ColType field is required." name="ColType">
<input type="hidden" value="false" id="ColType" name="ColType">

如您所见,它创建了一个值为 false 的隐藏复选框。这意味着,作为布尔类型,它在提交时始终具有 true 或 false 值。

标签: c#asp.net-coremodel-view-controller

解决方案


当您使用 ASP.NET Core 时,建议使用Tag Helpers

<div class="form-group">
    <label asp-for="@Model.ColName"></label>
    <input asp-for="@Model.ColName" type="checkbox" />
</div>

推荐阅读