将ID从所选项目传递到控制器

时间:2019-11-07 15:15:56

标签: javascript c# model-view-controller asp.net-core-2.2

我的视图上有一个脚本,用于将ID从所选值传递到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>

这是我的控制器上的功能:

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

选择更改事件有效,但与Get请求一起发送的参数groupId始终为0。我忘记了什么?

更新 cjp的答案可以解决问题。

我的第二个问题,现在过滤正在起作用,我碰到另一件事... 我是Java语言的新手,但是当我更改所选内容时,我在第二个DropDownList中看到了正确的金额,但为空,则不显示文本。

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

这有什么问题?

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

enter image description here

1 个答案:

答案 0 :(得分:2)

{Id:selectedGroup}表示您正在传递名称为Id的参数,该参数在您的方法中不存在。 可以将其替换为{groupId:selectedGroup},也可以将方法签名更改为:

    public ActionResult GetCategories(int Id)
相关问题