I have a controller that uses a ViewBag to bring the data into the view.
var _021CheckBox = dc.OptionsTbls.Where(a => a.Question_ID == 21).ToList();
ViewBag.CheckBoxfacilities = new SelectList(_021CheckBox, "ID", "QOption").ToList();
Then i have the View that's supposed to submit a string back to the controller but it only sends the first selected item. I even tried Javascript to combine the two but that did not work either. here's my view (both listboxfor and loop
//Loop
@for (int i = 0; i < ViewBag.CheckBoxfacilities.Count; i )
{
@Html.HiddenFor(model => model._021CheckBox[i], new { @id = "_021CheckBox" })
<input name="_021CheckBox" type="checkbox" value="@ViewBag.CheckBoxfacilities[i].Text" id="@ViewBag.CheckBoxfacilities[i].Value" /> @ViewBag.CheckBoxfacilities[i].Text <br />
}
// listboxfor
@Html.ListBoxFor(m => m._021CheckBox, new MultiSelectList(ViewBag.CheckBoxfacilities, "Value", "Text"), new { @Multiple = "multiple" })
//JavaScript that appends the value
<script>
var Values = [];
$('input[name=_021CheckBox]').change(function () {
if (this.checked) {
Values.push($(this).val() ";");
}
else {
Values.pop(this);
}
$('#_021CheckBox').val(Values).appendTo('form');
document.getElementById("_021CheckBox").value = Values;
});
</script>
here is my Model. I think maybe this is where i'm messing up
[Table("TBLMajorQuestions")]
public partial class TBLMajorQuestion
{
[Key]
public int ID { get; set; }
public string _021CheckBox { get; set; }
}
CodePudding user response:
I think i was trying to fit a square peg into a circle. The easiest thing to do is editvmy column from _021CheckBox
to _021aCheckBox
and to add two more columns into my table. _021bCheckBox
and _021cCheckBox
. Now i change them from strings to bits and update my model accordingly.
In the view, i took out all the extra javascript and did @html.CheckBoxFor(m => m._021aCheckBox)
. Done! Did the same for the other two checkboxes.