lundi 29 décembre 2014

How to find whcih checkboxes are selected and pass them to ActionResult in MVC?

I have a MVC5 app, and in one of my views, I have something like that:



<div id="subcatsform" class="form-group" style="visibility:hidden;">
@Html.LabelFor(m => m.Subcategories, new { @class = "col-md-3 control-label" })
<div id="subcats" class="col-md-9">

</div>
</div>


Then, in my JavaScript part, I do something like this in order to populate my empty div.



$(function () {

$("#CategoryID").on("change", function () {
var selected_option = $("#CategoryID option").filter(":selected").text();
$("#subcats").empty();

if (selected_option != "Please select a category") {
$("#subcatsform").css("visibility", "visible");

$.ajax({
url: "/Home/GetSubcategories",
dataType: "json",
data: {
cid: $("#CategoryID").val(),
},
success: function (data) {
$.each(data, function (key, value) {
var checkbox = '<input type="checkbox" name="subcategory" value="' + value.id + '"> ' + value.value + '<br />';
$("#subcats").append(checkbox);
});
}
});
}
else
{
$("#subcatsform").css("visibility", "hidden");
}
});

});


So, I simply check with category is previously selected, and then accordingly list all the subcategories found inside that category, and create input with type checkbox for each one of them. This works all fine, I'm able to get the appropriate subcategories when I change my category, and it creates the checkboxes for me.


The problem is that, later I don't know how to find out which checkboxes are selected, when the user presses the submit button in my view's form.


My ActionResult is defined like this:



public async Task<ActionResult> RegisterBusiness(BusinessViewModel model)


And inside my BusinessViewModel, I have a property defined like this:



public virtual ICollection<Subcategory> Subcategories { get; set; }


Any idea, how can I get the all checked checkboxes, and get their value property?





Aucun commentaire:

Enregistrer un commentaire