如何将Bootstrap输入框数据正确传递至.NET Core MVC控制器
实现输入框内容传递到Employees控制器的示例
下面提供两种适配Bootstrap 5 + .NET Core 6/MVC场景的实用实现方式:
方法一:JavaScript动态获取输入值跳转
给输入框添加ID标识,通过JS获取用户输入内容后拼接目标URL完成跳转:
<div class="input-group p-3"> <!-- 给输入框添加ID用于后续获取值 --> <input type="text" id="nameInput" class="form-control" placeholder="Enter Name"> <button class="btn btn-outline-primary" type="button" onclick="searchByName()">Search by Name</button> </div> <script> function searchByName() { // 获取输入框的内容并去除首尾空格 const inputValue = document.getElementById('nameInput').value.trim(); if (inputValue) { // 拼接路由地址,用encodeURIComponent处理特殊字符 location.href = '@Url.Action("Details", "Employees")?name=' + encodeURIComponent(inputValue); } else { alert("请输入要搜索的姓名"); } } </script>
对应的Employees控制器方法(参数名需与URL中的参数保持一致):
public IActionResult Details(string name) { // 在这里编写根据姓名查询员工的业务逻辑 return View(); }
如果偏好使用id作为参数名,只需把URL中的name改为id,控制器方法参数改为string id即可。
方法二:使用表单提交(更贴合MVC规范)
用<form>包裹输入组,通过GET请求自动传递参数,无需额外编写JS:
<form asp-controller="Employees" asp-action="Details" method="get" class="input-group p-3"> <input type="text" name="name" class="form-control" placeholder="Enter Name"> <button class="btn btn-outline-primary" type="submit">Search by Name</button> </form>
ASP.NET Core会自动处理表单参数的传递,控制器方法与方法一中的写法一致即可。若需要验证输入,可在前端添加简单判断,或在控制器内做参数校验。
内容的提问来源于stack exchange,提问作者BlueishVelvet
相关产品推荐
相关产品推荐

