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

ASP.NET Core MVC:@Html.DropDownList onChange传ViewBag参数报错求解

解决ASP.NET Core MVC DropDownList onchange传递ViewBag参数的问题

问题出在你直接在onchange事件里写ViewBag.CurrentSort——这是服务器端对象,渲染到前端后会被JS当成自身变量,但前端根本没有这个变量,所以报ReferenceError。下面是两种可行的解决方法:

方法一:直接将服务器端值渲染到JS代码中

把ViewBag.CurrentSort的实际值通过Razor语法直接输出到onchange的JS调用里,注意字符串类型要加引号包裹:

如果CurrentSort是字符串类型

@Html.DropDownList("PageSize", 
    new SelectList(new Dictionary<string, int> { { "10", 10 }, { "20", 20 }, { "30", 30 }, { "40", 40 }, { "50", 50 }, { "100", 100 } }, "Key", "Value", Convert.ToString(ViewBag.PageSize)), 
    new { id = "SearchPageSize", style = "width: 100px;", @onchange = $"AAA('{ViewBag.CurrentSort ?? ""}')" })

用$""字符串插值把服务器端值直接注入,?? ""是为了避免CurrentSort为空时出现语法错误。

如果CurrentSort是数字类型

直接输出即可,不用加引号:

@Html.DropDownList("PageSize", 
    new SelectList(new Dictionary<string, int> { { "10", 10 }, { "20", 20 }, { "30", 30 }, { "40", 40 }, { "50", 50 }, { "100", 100 } }, "Key", "Value", Convert.ToString(ViewBag.PageSize)), 
    new { id = "SearchPageSize", style = "width: 100px;", @onchange = $"AAA({ViewBag.CurrentSort ?? 0})" })

方法二:用自定义HTML属性传递值(更优雅)

把ViewBag.CurrentSort存到DropDownList的自定义data-*属性里,再在JS函数中读取:

第一步:修改DropDownList代码

@Html.DropDownList("PageSize", 
    new SelectList(new Dictionary<string, int> { { "10", 10 }, { "20", 20 }, { "30", 30 }, { "40", 40 }, { "50", 50 }, { "100", 100 } }, "Key", "Value", Convert.ToString(ViewBag.PageSize)), 
    new { id = "SearchPageSize", style = "width: 100px;", data_sort = ViewBag.CurrentSort ?? "", @onchange = "AAA(this)" })

Razor中用data_sort定义属性,渲染到前端会自动转成data-sort。

第二步:修改JS函数AAA

function AAA(element) {
    // 从自定义属性中获取值
    var currentSort = element.dataset.sort;
    // 执行你的业务逻辑
    console.log(currentSort);
}

这种方法更适合参数较多的场景,也能避免字符串拼接带来的语法问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:57:31