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

Categories

0 votes
539 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...