Search code examples
javascriptc#model-view-controllerasp.net-core-2.2

Passing Id from selected item to Controller


I have a script on my View to pass the Id from the selected value to my Controller :

<script type="text/javascript">
    $('#Group').change(function () {
        var selectedGroup = $("#Group").val();
        var categoriesSelect = $('#Category');
        categoriesSelect.empty();
        if (selectedGroup != null && selectedGroup != '') {
            $.getJSON('@Url.Action("GetCategories")', { Id: selectedGroup }, function (categories) {
                if (categories != null && !jQuery.isEmptyObject(categories))
                {
                    categoriesSelect.append($('<option/>', {
                        value: null,
                        text: ""
                    }));
                    $.each(categories, function (index, category) {
                        categoriesSelect.append($('<option/>', {
                            value: category.Value,
                            text: category.Text
                        }));
                    });
                 };
            });
        }
    });
</script>

This is the function on my Controller :

    [HttpGet]
    public ActionResult GetCategories(int groupId)
    {
        //...
    }

The selection change event works but the parameter groupId that is send with th Get request is always 0. What did I forgot?

Update The answer from cjp did the trick.

My second question, now the filtering is working I run into another thing... i'm new to javascript but when I change the selected I see the right amount in the second DropDownList, but empty, the text is not shown..

    [HttpGet]
    public ActionResult GetCategories(int groupId)
    {
        return Json(GetCategoriesByGroupId(groupId)/*, JsonRequestBehavior.AllowGet*/);
    }

What is wrong with this?

$.each(categories, function (index, category) {
    categoriesSelect.append($('<option/>', {
        value: category.Value,
        text: category.Text
     }));
});

enter image description here


Solution

  • { Id: selectedGroup } indicates that you are passing a parameter with the name Id, that parameter does not exist in your method. Either replace that by {groupId : selectedGroup } or change your method signature to:

        public ActionResult GetCategories(int Id)