You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Onchange与Ajax Post将下拉框选中值传递至Controller?

问题描述

已通过onchange事件获取到下拉框的ID值,但Ajax POST请求无法将该值传递到后端Action方法中。

现有代码

JavaScript代码

$(document).ready(function() {
    $("#TestID").change(function() {
        debugger;
        var TestSampleID = $(this).val();
        $("#TestID").empty();
        $.ajax({
            type: "Post",
            url: "/MyController/MyAction?iTestID=" + TestSampleID,
            contentType: "html",
            success: function(response) {
                $("#hds").append(response);
            },
            error: function(jqXHR, textStatus, errorThrown) {}
        })

    })
});

Razor视图代码

@if(ViewBag.TestData != null) {
    @Html.DropDownListFor(m => m.TestID, ViewBag.TestData as SelectList, new {
        @class = "form-control", @required = "required"
    })
}

ASP.NET Core后端Action方法

[HttpPost]
public IActionResult MyAction (int iTestID)
{
    
 ///业务逻辑代码
    
}
问题分析与修复方案

导致参数无法正确传递的核心问题有以下几点:

  1. contentType设置错误:POST请求传递参数时,设置contentType: "html"不符合参数绑定的格式要求,会导致后端无法正确解析参数。
  2. 错误清空下拉框:获取值后执行$("#TestID").empty();会直接清空下拉选项,可能引发后续逻辑异常,完全没必要保留这行代码。
  3. 参数传递方式不规范:虽然URL拼接参数在POST请求中能生效,但更规范的做法是将参数放在请求体中,避免潜在的路由或编码问题。

修复后的JavaScript代码

$(document).ready(function() {
    $("#TestID").change(function() {
        var TestSampleID = $(this).val();
        $.ajax({
            type: "Post",
            url: "/MyController/MyAction",
            contentType: "application/x-www-form-urlencoded",
            data: { iTestID: TestSampleID },
            success: function(response) {
                $("#hds").append(response);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("请求错误:" + textStatus + "," + errorThrown);
            }
        })
    })
});

可选:JSON格式传递参数

如果偏好使用JSON格式传递参数,可修改如下:

$(document).ready(function() {
    $("#TestID").change(function() {
        var TestSampleID = $(this).val();
        $.ajax({
            type: "Post",
            url: "/MyController/MyAction",
            contentType: "application/json",
            data: JSON.stringify({ iTestID: TestSampleID }),
            success: function(response) {
                $("#hds").append(response);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("请求错误:" + textStatus + "," + errorThrown);
            }
        })
    })
});

此时后端Action需要添加[FromBody]特性来绑定JSON参数:

[HttpPost]
public IActionResult MyAction ([FromBody] int iTestID)
{
    //业务逻辑代码
}
额外注意事项
  • 确认控制器、Action名称拼写正确,URL路径/MyController/MyAction要与实际路由规则匹配(若使用区域,需加上区域路径,如/AreaName/MyController/MyAction)。
  • 检查后端是否启用了必要的请求解析中间件(如app.UseRouting()、app.UseAuthorization()等),确保请求能正常到达Action方法。

内容的提问来源于stack exchange,提问作者cr7oo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:55:42