c# - 为什么我的复选框没有将它们的值传递给 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 值。
解决方案
当您使用 ASP.NET Core 时,建议使用Tag Helpers:
<div class="form-group">
<label asp-for="@Model.ColName"></label>
<input asp-for="@Model.ColName" type="checkbox" />
</div>
推荐阅读
- r - 在折线图 R 中显示值
- android - Room 无法验证数据完整性,即使在卸载应用程序然后重新安装后也是如此
- c++ - C++ 上的并行并不像 C# 那样快
- verilog - 左移直到 MSB 为 1:超出循环计数限制。条件永远不会是假的
- powershell - 记录从单个父 ps 脚本调用的多个子 ps 脚本的输出的最佳简单方法是什么?
- c - 如何删除C中的特定记录
- r - 如何按一列分组并获取其他列的方法
- javascript - js类返回未定义的对象
- html - CSS区分悬停在元素上和它的 ::before 伪元素
- javascript - 在制作 Leaflet 地图时,如何将 GeoJSON 坐标拉取并转换为 latLng?