在 Ajax 中使用 GET 方法将参数获取到控制器中

Get parameter into controller by using GET method in Ajax

我在 cshtml 文件中有这段代码

@using (Html.BeginForm("UserPermission", "UserPermision", new { area = "Admin", id = "cbbDpm", name = "cbbDpm" }, FormMethod.Post))
   {
      @Html.DropDownListFor(m => m.Dept, new SelectList(Model.Dept, "DepartmentName", "DepartmentName"), "-- Select Department --", new { @class = "form-control w-100", @id = "cbbDpmt", @name = "cbbDpmt" })
   }
...
<div id="partialDiv">
   @Html.Partial("_Table")
</div>
...
<script>
    $(document).ready(function () {
        $("#cbbDpmt").on("change", function () {
            $.ajax(
                {
                    url: '/Admin/UserPermision/CBBSelectedChange?dpmname' + $(this).val(),
                    type: 'GET',
                    data: "",
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        $("#partialDiv").html(data);
                    },
                    error: function () {
                        alert("error");
                    }
                });
        });
    });
</script>

在控制器中,我有:

[HttpGet]
public PartialViewResult CBBSelectedChange(string dpmname)
{
 List<AdminUserPermission> userModels = DatabaseServer.ConvertDataTable<AdminUserPermission>(DatabaseServer.Read_Table(@"SELECT * 
                                                          FROM dbo.tblWFX_UserGroup AS gr 
                                                          JOIN dbo.tblWFX_Department AS dpm ON gr.DepartmentName = dpm.DepartmentID 
                                                          WHERE dpm.DepartmentName = " + dpmname, false));
 Session["selectedDept"] = dpmname;
 AdminUserPermissionParty adminUserPermissionParties = new AdminUserPermissionParty();
 adminUserPermissionParties.UserPermisionModel = userModels;
 return PartialView("_Table", adminUserPermissionParties);
}

我想将 cshtml 中组合框中的选定项目放入控制器中的函数中。我尝试研究了很多次,但我无法将 cbb 中的选定值放入字符串 dpmname 中。 请帮助我。

您需要使用 [FromUri]

[HttpGet]
public PartialViewResult CBBSelectedChange([FromUri] string dpmname)

并且还更改 Ajax 调用如下:

 $.ajax(
        {
            url: '/Admin/UserPermision/CBBSelectedChange?dpmname=' + $(this).val(),
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $("#partialDiv").html(data);
            },
            error: function () {
                alert("error");
            }
        });

参见:https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api