문제

As I am new to MVC framework, I have been spending a couple of hours to generate a check box list in a View file. Finally, I could figure it out well. Here is my code:

 @foreach (var item in Model.GetRoleNames)
        {
            @Html.CheckBox("chk_" + item.Value, new { value = item.Value })@item.Text<br />
        }

But, I need to detect which of them is selected and if all the ckeckboxes are left unchecked, then preventing some operations.

Question: How can I get the checked items when I am within a controller action?

도움이 되었습니까?

해결책

As the others said, you should use a Boolean value as the second parameter to CheckBox to indicate the checked status. A bit of string manipulation should help you get the ids of the selected check boxes..

First lets change the way the checkbox helper is used

<div id='myCheckboxDiv'>
 @foreach (var item in Model.GetRoleNames)
 {
   @Html.CheckBox("chk_" + item.Value, false)@item.Text<br />
 }
</div>

As you can see, I have set the second parameter to false and wrapped the mix in a div

And, when you want to get the ‘values’ associated with the selected checkboxes

var values = $(‘# myCheckboxDiv’).find('input:checkbox:checked').map(function () {

  // get the name ..
  var nameOfSelectedItem = this.attr('name');

  // skip the ‘chk_’ part and give me the rest
  return nameOfSelectedItem.substr(4);

}).get();

I am assuming item.Value to be a number. If its is not, please remove the white spaces using C#

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top