jeudi 1 janvier 2015

How to pass the values of the checkboxes to ActionResult in MVC5?

I have an MVC5 app, and in my view, I have a code like this:



<div class="form-group">
@Html.LabelFor(model => model.CategoryID, "Category", htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-9">
@Html.DropDownList("CategoryID", null, "Please select a category", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
</div>
</div>
<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, I have a JavaScript code which populates the subcategories according to the previously selected category. I achieve it with the following code segment:



$(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");
}
});
});


The point is that, until there everything works fine, and for each selected category, I get the list of subcategories correctly and create checkboxes with each one of them, where the name attribute as you can see is equal to subcategory and the value attribute is equal to the actual id of the subcategory.


What I want to do next, is that I want to get the value attributes of the checked checkboxes (meaning selected subcategories), and pass that to my controller. My ActionResult is defined like this:



public async Task<ActionResult> RegisterBusiness(BusinessViewModel model)


Inside the BusinessViewModel, I have a property like this:



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


And, finally my Subcategory model is defined like this:



public class Subcategory
{
public int SubcategoryID { get; set; }

public string SubcategoryName { get; set; }

public string SubcategoryDescription { get; set; }

[ForeignKey("Category")]
[Display(Name = "Category")]
public int CategoryID { get; set; }

public virtual Category Category { get; set; }

[NotMapped]
public bool IsSelected { get; set; }
}


If someone can help me pass the values of the selected checkboxes into my RegisterBusiness ActionResult, and then store them inside my ICollection<Subcategory> Subcategories property, I would be glad.





Aucun commentaire:

Enregistrer un commentaire