单击复选框时,使用 jQuery 提交表单,但复选框始终返回 null。
我有以下剃刀代码:
@using (Html.BeginForm("Index", "HumanResource", new { type = ViewBag.CurrentType }, FormMethod.Post, new { id = "form1" }))
{
<label class="custom-control custom-checkbox" for="Filter">
@Html.CheckBox("Filter", new { @class = "custom-control-input" })
<span class="custom-control-indicator"></span>
Choose
</label>
}
// Scripts
<script>
$('#form1 :checkbox').change(function() {
$("#form1").submit();
});
</script>
控制器
public async Task<ActionResult> Index(FormCollection fc,int? Filter)
{
// leftFilter is always null
}
当提交表单时,浏览器将发送true
或false
用于filter
输入表单数据,到窗体action
URL(其中处理表单提交操作方法)。您正在使用一个可为空的 int( int?
) 作为参数来接受 的值filter
。模型绑定器无法将布尔值映射到可为空的 int。它如何知道在数字参数中为 true /false 分配什么值?它可以将传入的布尔值映射到仅布尔参数。
因此,将您的参数类型更改为bool
.
[HttpPost]
public async Task<ActionResult> Index4(FormCollection fc, bool filter)
{
//to so : return something
}
现在,当提交表单时,filter
参数将填充一个值。
建议:当用户单击复选框时提交表单似乎是一种糟糕的用户体验恕我直言,如果用户想要更改怎么办?添加一个单独的“搜索”按钮并在用户选择复选框后单击该按钮时提交表单如何?或者也许考虑一些客户端/ajax 类型的过滤。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句