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

ASP.NET Web应用中如何重新填充/刷新<select asp-items>下拉列表

实现ASP.NET MVC下拉列表的动态刷新

没问题,我来帮你搞定这个下拉列表刷新的需求!首先得理清你当前代码的局限:你的CaptureDevices是静态字段,会在应用启动时初始化一次,之后就不会自动更新了。要实现动态刷新,我们需要通过AJAX异步请求后端最新数据来更新下拉列表,具体步骤如下:

1. 在控制器中添加获取最新设备列表的接口

首先给你的MvcController加一个Action,专门用来返回最新的捕获设备ID列表:

[HttpGet]
public JsonResult GetCaptureDevices()
{
    // 每次请求都重新调用API获取最新设备
    var latestDevices = _api.GetCaptureDeviceIds();
    return Json(latestDevices, JsonRequestBehavior.AllowGet);
}

如果你使用的是ASP.NET Core,不需要JsonRequestBehavior.AllowGet,直接返回Json(latestDevices)即可。

2. 给视图中的下拉列表添加标识并准备触发按钮

修改你的Index.cshtml,给下拉列表加一个唯一ID,再添加一个刷新按钮(也可以根据需求改成自动刷新,比如定时调用):

<select id="captureDeviceDropdown" asp-items="@(new SelectList(MvcController.CaptureDevices))">
</select>
<button id="refreshDevicesBtn">刷新设备列表</button>

3. 用JavaScript实现异步刷新逻辑

你可以选择jQuery或者原生JavaScript来实现,这里两种方案都给你:

方案一:使用jQuery

$(function() {
    // 绑定按钮点击事件
    $('#refreshDevicesBtn').click(function() {
        // 调用后端接口(用Url.Action生成可靠路径)
        $.get('@Url.Action("GetCaptureDevices", "MvcController")', function(devices) {
            // 清空现有选项
            $('#captureDeviceDropdown').empty();
            // 遍历添加新选项
            $.each(devices, function(index, deviceId) {
                $('#captureDeviceDropdown').append(`<option value="${deviceId}">${deviceId}</option>`);
            });
        }).fail(function() {
            alert('刷新设备列表失败,请稍后重试');
        });
    });
});

方案二:原生JavaScript(无需jQuery)

document.addEventListener('DOMContentLoaded', function() {
    const refreshBtn = document.getElementById('refreshDevicesBtn');
    const dropdown = document.getElementById('captureDeviceDropdown');

    refreshBtn.addEventListener('click', async function() {
        try {
            // 发起GET请求获取最新设备
            const response = await fetch('@Url.Action("GetCaptureDevices", "MvcController")');
            const devices = await response.json();

            // 清空下拉列表
            dropdown.innerHTML = '';

            // 逐个添加新选项
            devices.forEach(deviceId => {
                const option = document.createElement('option');
                option.value = deviceId;
                option.textContent = deviceId;
                dropdown.appendChild(option);
            });
        } catch (error) {
            console.error('刷新失败:', error);
            alert('刷新设备列表失败,请检查控制台信息');
        }
    });
});

几个关键注意点

  • 路由可靠性:用@Url.Action生成请求路径,避免硬编码控制器和Action名称,防止路由配置变化导致请求失败。
  • 异步优化:如果_api.GetCaptureDeviceIds()支持异步调用,建议把Action改成异步版本:
    public async Task<JsonResult> GetCaptureDevices()
    {
        var latestDevices = await _api.GetCaptureDeviceIdsAsync();
        return Json(latestDevices);
    }
    
  • 权限控制:如果这个接口需要用户授权,记得添加对应的授权特性(比如[Authorize]),确保请求携带合法的身份信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:47:14