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

.NET Core 8 MVC中如何将chtml文件关联JavaScript文件

解决.NET Core MVC中cshtml与wwwroot JavaScript关联及JS实现下拉列表的方法

一、关联cshtml与wwwroot中的JavaScript文件

有两种实用方式:

1. 全局引入(通过_Layout.cshtml)

如果你的JS文件是多个页面共用的,直接在_Layout.cshtml的</body>标签前添加引用即可,~/会自动映射到wwwroot目录:

<script src="~/js/your-script-file.js"></script>

2. 单页面局部引入

如果JS只在当前Index页面使用,就在Index.cshtml末尾添加@section Scripts块(前提是_Layout.cshtml中包含@RenderSection("Scripts", required: false)代码):

@section Scripts {
    <script src="~/js/role-dropdown.js"></script>
}

二、用JavaScript实现自定义下拉列表

先替换原有@Html生成的下拉结构,再用JS实现交互逻辑:

1. 修改Index.cshtml的HTML结构

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <label class="form-label">Role</label>
    <!-- 自定义下拉容器 -->
    <div class="custom-dropdown">
        <div class="dropdown-trigger" id="roleTrigger">Select Role</div>
        <ul class="dropdown-options" id="roleOptions" style="display: none;">
            <!-- JS将动态填充选项 -->
        </ul>
    </div>
</div>

@section Scripts {
    <script src="~/js/role-dropdown.js"></script>
}

2. 在wwwroot/js/role-dropdown.js中编写逻辑

// 若需从后端获取枚举值,可参考后续注意事项的传值方式
const roles = ["Admin", "Editor", "Viewer", "Guest"];

document.addEventListener('DOMContentLoaded', function() {
    const trigger = document.getElementById('roleTrigger');
    const optionsList = document.getElementById('roleOptions');
    
    // 动态生成下拉选项
    roles.forEach(role => {
        const li = document.createElement('li');
        li.textContent = role;
        li.classList.add('dropdown-option');
        
        // 点击选项更新触发器文本并隐藏列表
        li.addEventListener('click', function() {
            trigger.textContent = role;
            optionsList.style.display = 'none';
            // 可在此添加选中后的业务逻辑,比如存入隐藏input用于表单提交
        });
        optionsList.appendChild(li);
    });
    
    // 点击触发器切换列表显示状态
    trigger.addEventListener('click', function() {
        optionsList.style.display = optionsList.style.display === 'none' ? 'block' : 'none';
    });
    
    // 点击页面其他区域隐藏下拉列表
    document.addEventListener('click', function(e) {
        if (!trigger.contains(e.target) && !optionsList.contains(e.target)) {
            optionsList.style.display = 'none';
        }
    });
});

3. 添加基础样式(可选)

将以下代码添加到wwwroot/css/site.css或单独的CSS文件中:

.custom-dropdown {
    position: relative;
    width: 200px;
    margin: 0 auto;
}

.dropdown-trigger {
    padding: 8px 12px;
    border: 1px solid #ced4da;
    border-radius: 4px;
    cursor: pointer;
    background-color: white;
}

.dropdown-options {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    border: 1px solid #ced4da;
    border-top: none;
    border-radius: 0 0 4px 4px;
    background-color: white;
    list-style: none;
    padding: 0;
    margin: 0;
}

.dropdown-option {
    padding: 8px 12px;
    cursor: pointer;
}

.dropdown-option:hover {
    background-color: #f8f9fa;
}

三、注意事项

  • 若需要从后端获取ERoles枚举数据,可在Index.cshtml中把枚举转成JSON传给JS:
    @section Scripts {
        <script>
            const roles = @Html.Raw(Json.Serialize(Html.GetEnumSelectList<ERoles>().Select(x => x.Text)));
        </script>
        <script src="~/js/role-dropdown.js"></script>
    }
    
  • 示例使用原生JavaScript,无需依赖jQuery,若项目已引入jQuery,也可改用jQuery语法实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:27:03