如何在C#(CSHTML)中使用jQuery变量值?
解决方法
首先明确:前端JS里的selectedIndex是客户端浏览器中的变量,无法直接在服务器端C#代码中使用,必须通过HTTP请求将这个值传递到后端控制器方法中。下面是分步修正方案:
1. 修复下拉框的HTML生成代码
你的Razor代码生成的<option>标签缺少value属性,且未包裹在<select>标签内,这会导致dropdownList.value无法获取正确值,先修正这部分:
@if (Model.Templates != null) { <select id="betreffDropdown"> @foreach (var template in Model.Templates.Distinct()) { <option value="@template.Item2">@template.Item2</option> } </select> }
2. 用AJAX将选中值传递到后端控制器
修改JS代码,当下拉框选中状态变化时,通过AJAX请求将选中值发送到后端的GetValueOfDropdown方法:
let dropdownList = document.getElementById('betreffDropdown'); dropdownList.onchange = (ev) => { let selectedValue = dropdownList.value; // 发送AJAX请求,替换YourControllerName为实际控制器类名 fetch('/YourControllerName/GetValueOfDropdown?selectedIndex=' + encodeURIComponent(selectedValue)) .then(response => response.json()) .then(data => { // 此处可处理后端返回的模板内容,比如更新页面元素 console.log('匹配的模板内容:', data); }) .catch(error => { console.error('请求失败:', error); }); }
3. 修正后端控制器的空值异常问题
你的控制器方法未处理SingleOrDefault返回null的情况,会触发空引用异常,补充空值判断逻辑:
private readonly TemplatesVM templatesVM; // 确保通过构造函数注入TemplatesVM实例 public YourControllerName(TemplatesVM templatesVM) { this.templatesVM = templatesVM; } [HttpGet] public IActionResult GetValueOfDropdown(string selectedIndex) { if (string.IsNullOrEmpty(selectedIndex)) { return BadRequest("选中值不能为空"); } var templateList = templatesVM.Templates?.Distinct().ToList(); if (templateList == null || !templateList.Any()) { return NotFound("无可用模板数据"); } var matchedTemplate = templateList.SingleOrDefault(x => x.Item2 == selectedIndex); if (matchedTemplate == null) { return NotFound("未找到匹配的模板"); } return Json(matchedTemplate.Item1); }
替换YourControllerName为实际的控制器类名
备选方案:表单同步提交(无需异步)
如果不需要异步更新页面,可将下拉框放入表单,通过提交表单传递选中值:
<form method="get" asp-action="GetValueOfDropdown" asp-controller="YourControllerName"> @if (Model.Templates != null) { <select name="selectedIndex" id="betreffDropdown"> @foreach (var template in Model.Templates.Distinct()) { <option value="@template.Item2">@template.Item2</option> } </select> } <button type="submit">确认选择</button> </form>
提交表单后,后端控制器的selectedIndex参数会自动获取下拉框的选中值。
内容的提问来源于stack exchange,提问作者citr0q
相关产品推荐
相关产品推荐

