Reputation: 26
I spent many days trying to pass the information from the View to the Controller
using @Html.CheckBox()
I have a textarea and a loop of checkboxes (we don't know how many). I can manage the textarea but not the checkboxes.
The View:
@using (Html.BeginForm("ProviderConfigurationTool", "Admin"))
{
<div>
<strong>Custom Rule </strong>
@Html.TextArea("CustomRule", new { rows = 12, columns = 30 })
<br />
</div>
foreach (var item in ViewBag.farmlist)
{
<table>
<tr>
<td style="border-bottom: solid 1px #EBEFF6">
<p>@item</p>
@Html.CheckBox("@item");
<!-- <input id="@item" name="@item" type="checkbox" onclick="addingFarms('@item')" class="farms" /> -->
</td>
</tr>
</table>
}
<input type="submit" value="Submit and close" onclick="refreshParent();self.close()" />
}
@{Html.EndForm();}
As you can I tried also with the normal html code using "type=checkbox"
The Controller:
[HttpPost]
public ActionResult Create(string CustomRule, FormCollection collection)
{
string results = collection["Blanks"]; // it does not work
newRule.Key = CustomRule; // it works
}
The other idea was using javascript and trying to create a List to pass to the controller like that
View:
input id="@item" name="@item" type="checkbox" onclick="getFarms('@item')" class="farms"
function getFarms() {
var inputs = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
//Here I am blocked because I don't know how to pass a new list to the controller
}
If somebody already got this problem or have an idea, please help me!
Upvotes: 0
Views: 115
Reputation: 498
You can use ajax for this.
In the .cshtml
page:
<input type='checkbox' name='ch' value='@item'>
In JQuery:
var it=$('ch:checked').serialize(); $.ajax('yourcontoroller/youractionname',it)
In your Controller:
public ActionResult Create(string customRule, string[] ch)
{
...
}
Upvotes: 2
Reputation: 3204
Obviously, HTML forms are used to collect user input. For check-boxes, the value property only has meaning when submitting a form. If a check-box is in checked state when the form is submitted, the name of the check-box is sent along with the value of the value property (if the check box is not checked, no information is sent). So, if you assign a name to check-boxes, your Controller receives and array of checked values by the name. So, the declaration of the check-boxes should something like this.
<input name="checkboxes" type="checkbox" value="@item" />
and your Controller
public ActionResult Create(string customRule, string[] checkboxes)
{
...
}
The checkboxes
contains all values which are checked.
Upvotes: 2