CheckBox在ASP.NET MVC中始终返回null

时间:2018-08-13 14:23:30

标签: jquery html asp.net-mvc checkbox

当单击复选框时,表单是使用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
}

1 个答案:

答案 0 :(得分:3)

提交表单后,浏览器会将表单数据中用于true输入的falsefilter发送到表单action URL(处理表单提交)。您正在使用可为null的int(int?)作为参数来接受filter的值。模型绑定器无法将布尔值映射到可为null的int。如何知道在数字参数中为true / false分配什么值?它可以将传入的布尔值映射为仅一个布尔参数。

因此,将参数类型更改为bool

[HttpPost]
public async Task<ActionResult> Index4(FormCollection fc, bool filter)
{
    //to so : return something
}

现在,提交表单后,filter参数将填充一个值。

建议:当用户单击复选框时提交表单似乎是不好的用户体验,恕我直言,如果用户要更改怎么办?当用户在选中复选框后单击该按钮时,如何添加单独的“搜索”按钮并提交表单?或者也许考虑某种客户端/ ajax过滤。