Based on Darin’s answer to my question Ho to display multiple checkbox selection based on user's selection from dropdown?
I am displaying multiple checkboxes based on dropdown selection.
Now, once the user post the form (with multiple inputs) that i have on my page, i collect all the data using FormCollection. And the problem i have is how can i pull those selected checkbox values from formcollection? The number of checkbox will change on different selection from the drop-down, so i think requesting each checkbox value will not work.
Can anyone help me with this problem.
The flow is as shown below:
Properties in Model
public class Subcategory
{
public string Name { get; set; }
public int ID { get; set; }
public bool Flag { get; set; }
}
Displaying PartialView in actual view where other form inputs are there:
<div id="checkboxlist">
@if (Model.SubCategories != null)
{
@Html.Partial("SubCategories", Model.SubCategories)
}
</div>
PartialView SubCategories.cshtml
@model IEnumerable<MyProject.Entities.Subcategory>
@{
// we change the HTML field prefix so that input elements
// such as checkboxes have correct names in order to be able
// to POST the values back
ViewData.TemplateInfo.HtmlFieldPrefix = "checkboxlist";
}
<span>subcategory</span>
<div id="subcategories" style="margin-left: 130px;margin-top: -20px;" data-role="fieldcontain">
<fieldset data-role="controlgroup">
@Html.EditorForModel()
</fieldset>
</div>
EditorTemplates Subcategory.cshtml
@model MyProject.Entities.Subcategory
<div class="editor-label">
@Html.CheckBoxFor(c => c.Flag, new { type = "checkbox" })
<label for="@Model.ID">@Model.Name</label>
@Html.HiddenFor(c => c.Flag)
@Html.HiddenFor(c => c.ID)
@Html.HiddenFor(c => c.Name)
</div>
jquery to display checkboxes based on dropdown selection:
$('#Category').change(function () {
var subcategoriesUrl = $(this).data('subcategoriesurl');
var categoryId = $(this).val();
$('#checkboxlist').load(subcategoriesUrl, { category: categoryId });
});
Don’t use
FormCollection. That’s weakly typed. Use view models. Like this:Also notice that you have an inconsistency between the field prefix that you are using in your partial:
and the view model collection property:
Model.BusinessSubCategories. So make sure you fix the prefix to use the correct property name if you want the default model binder to be able to populate this property when you post back.