Skip to content Skip to sidebar Skip to footer

Checkbox To Enable Or Disable A List Box

I have a checkbox on my ASP.NET MVC page that I create like:
@Html.CheckBoxFor(m => m.allUsers, new { Name = 'allUsersCheck' }) @Html.LabelFor(m => m.allU

Solution 1:

Because you are using the Id selector of '#allUsersCheck'. The checkbox does not have an Id attribute unlike your list box(?).

@Html.CheckBoxFor(m => m.allUsers, new { Name = "allUsersCheck" })

Try the following with an Id attribute:

@Html.CheckBoxFor(m => m.allUsers, new { Name = "allUsersCheck", Id = "allUsersCheck" })

Solution 2:

Ok. Took me a while to figure out the entire list of things I need to do.

Here's all I did to finally get it working.

  1. Firstly, I needed this jquery library being used.
<scripttype="text/javascript"src="http://code.jquery.com/jquery-1.8.2.js"></script>
  1. Then I had to create a function under the above jquery inclusion
<scripttype="text/javascript">

    $(function () {
        $("#allUsersCheck").change(function () {
            $("#lbUsers").find("option").prop("selected", this.checked)

        });
    });
</script>

In the above you'll see allUsersCheck is the checkbox element's id and lbUsers is the id for the ListBoxFor element.

  1. The next thing is, in my .cshtml I needed to use/create the listboxfor / checkbox elements. This is how I did it
      <b>Users </b><br />
      @Html.ListBoxFor(x => x.selectedUsers, Model.ListofUsers, new { style = "width:200px", size = 10, id = "lbUsers" })
      <br />


      <div>
           @Html.CheckBoxFor(m => m.allUsers, new { id = "allUsersCheck" })
           @Html.LabelFor(m => m.allUsers)
      </div>

I also used a bool flag as part of my model. allUsers is the flag. The bool flag was needed for something else in the controller code and not for UI reasons.

I am not sure if this is the best method. But this is the method I could get it working.

Thanks to the guys who helped me in this process get this working. Obviously not without them.

Post a Comment for "Checkbox To Enable Or Disable A List Box"