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
相关产品推荐
相关产品推荐

