Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...