Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC Binding to checkbox

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;  }
}

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

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

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.

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.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try like this:

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

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; }
}

you could:

<% 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
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...