I am having trouble with a simple Visual Basic Code for MVC using Check Boxes. I am trying to create a Form where the user could choose which Office Department will have access to a particular Document.
The data gets displayed correctly from the Model to Controller to View. However, I cannot get the clicked values from the View back to the Controller.
Here is the Model:
Public Class Department <Required> <Display(Name:="Department ID")> Public Property DepartmentID As Integer = 1 <Required> <Display(Name:="Department Name")> Public Property DepartmentName As String = "" <Required> <Display(Name:="Department Image")> Public Property DeptImage As String = "" Public Property IsSelected As Boolean = False End Class
Here is the View
<section class="checkBoxListFor"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Access Rights</h3> </div> <div class="panel-body"> @For Each oDept As Department In Model.DeptList @<text> @Html.CheckBoxFor(Function(m) oDept.IsSelected) @oDept.DepartmentName @Html.HiddenFor(Function(m) oDept.DepartmentID) @Html.HiddenFor(Function(m) oDept.DepartmentName) <br /> </text> Next </div> </div> </section>
I have read an article here about NOT using a For Each Loop to display the collection of Form Controls since when you look at the generated HTML Code, the "name" will not be correct and hence it won't bind to the Controller when POST Back is called. The problem is I do not know how to do it.
Any help is appreciated on how to properly implement this simple task. Thanks!
Ok, I found the problem. It is because of the
tag. The checkbox collection loop is outside of these tags. Although all of the fields and the Check Boxes are under the html helper "BeginForm" the checkboxes loop is outside of the tag.
This is the reason why these checkbox's values were never passed back to the controller during post back.
I put the loop inside the tag and viola, they are now populated on the "POST" controller.