MVC绑定到复选框 [英] MVC Binding to checkbox

查看:141
本文介绍了MVC绑定到复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个这么多的问题,但他们都不去了,或似乎走了我的方案。我有一个模型:

I have found so many questions about this, but none of them go over or seem to go over my scenario. I have a model:

public class CheckBoxModel
{
            public int Id{ get; set; }
    public bool IsSelected { get; set;  }
}

在随后尝试和我的IsSelected布尔绑定到这样一个复选框:

In then try and bind my IsSelected bool to a checkbox like this:

<%= Html.CheckBox("IsSelectedCheck",Model.IsSelected)%>

我有一个页面上的许多项目,它们都旁边有一个复选框,所有我试图做的是传回给控制器哪些已选定的项目,所有的ID。

I have lots of items on a page, they all have a checkbox next to them, all i am trying to do is pass back to the controller all the id's of the items and which ones have been selected.

目前,IsSelected的值始终为false。应该Html.CheckBox每个用户切换的复选框时设置Model.IsSelected的值。

At the moment, the value of IsSelected is always false. Should Html.CheckBox set the value of Model.IsSelected each time the user toggles the checkbox.

感谢

推荐答案

尝试这样的:

<%= Html.CheckBoxFor(x => x.IsSelected) %>

此外,如果你想沿着ID传递不要忘了这样做的:

Also if you want to pass along the id don't forget to do so:

<%= Html.HiddenFor(x => x.Id) %>

如果你有这些的集合:

And if you had a collection of those:

public class MyViewModel
{
    public CheckBoxModel[] CheckBoxes { get; set; }
}

您可以:

<% for (var i = 0; i < Model.CheckBoxes.Length; i++) { %>
    <div>
        <%= Html.HiddenFor(x => x.CheckBoxes[i].Id) %>
        <%= Html.CheckBoxFor(x => x.CheckBoxes[i].IsSelected) %>
    </div>
<% } %>

这将成功地绑定到:

which will successfully bind to:

[HttpPost]
public ActionResult MyAction(MyViewModel model) 
{
    // model.CheckBoxes will contain everything you need here
    ...
}

这篇关于MVC绑定到复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆