mardi 1 novembre 2016

Pass selected checkboxes ids to controller ajax mvc

in my mvc 5 app, I have a form with many checkboxes in my view.

View

  @foreach (var item in Model.BudgetSubCategory.Where(x => x.CategoryID == "01"))
            {

                <input type="checkbox" id="@item.SubCategoryID" name="@checkboxName" value="@item.SubCategoryID" />

                <label for="optionId">@item.SubCategoryDescription</label>

            }

            @foreach (var item in Model.BudgetSubCategory.Where(x => x.CategoryID == "02"))
            {

                <input type="checkbox" id="@item.SubCategoryID" name="@checkboxName" value="@item.SubCategoryID" />

                    <label for="optionId">@item.SubCategoryDescription</label>

            }

This code generates a list of checkboxes. I need to pass the id of selected checkboxes to my controller and then to save the records to my db.

My controller

 public ActionResult Create(IEnumerable<int> SubCategories)
    {

        foreach (int subId in SubCategories)

        {
            ViewBag.subcid = subId.ToString();
            var budgetdetails = new BudgetDetails

            {
                BudgetID = budgetmaster.Budget.BudgetID,
                SubCategoryID = ViewBag.subcid
            };

            db.BudgetDetails.Add(budgetdetails);
            db.SaveChanges();
        }

        return View();

    }

I have a ajax post according to this

$(document).ready(function () {
$('#postBtn').on('click', function () {
    var subsid= [];
    $('input:checked').each(function () {

        subsid.push($(this).attr("value"));
    });
    $.ajax({
        url: '@Url.Action("Create", "Budgets")',
        type: "POST",
        data: {SubCategories:subsid},
        dataType: "json",
        traditional:true,
        success: function () {
            alert("ajax request to server succeed");
        }
    });
  });
});

But It doesn't work. It passes 37 items and not the selected ids from checkboxes and in the table of the db it saves records only for the first main category from checkboxes. Any idea?




Aucun commentaire:

Enregistrer un commentaire