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

Asp.Net Core中如何在表单Post中携带输入框内容?

解决Asp.Net Core MVC表单提交搜索参数问题

不需要在Url.Action里硬编码搜索参数,只需要给输入框添加name属性,表单提交时会自动携带输入值到后台。具体修改如下:

修改后的表单代码

<form method="post" action="@Url.Action("Index", "Home")">
  <input class="form-control me-sm-2" type="text" placeholder="Enter Name" name="searchString">
  <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
</form>

关键说明

  • 给输入框添加name="searchString":HTML表单提交时,只有带name属性的控件值才会被包含在请求中,后台Action方法就能通过同名参数接收这个值。
  • 移除Url.Action中的searchString参数:这个参数是生成URL时的静态值,无法动态获取输入框的实时内容,完全没必要在这里设置。

后台Action示例

确保你的HomeController里的Index方法能接收POST请求和searchString参数:

[HttpPost]
public IActionResult Index(string searchString)
{
    // 这里处理搜索逻辑,过滤你的IEnumerable集合
    var filteredItems = _yourService.GetItems().Where(item => item.Name.Contains(searchString));
    return View(filteredItems);
}

如果需要同时支持GET和POST搜索(比如刷新页面时保留搜索参数),可以把Action改成同时支持两种请求方式:

[HttpGet]
[HttpPost]
public IActionResult Index(string searchString = null)
{
    var items = _yourService.GetItems();
    if (!string.IsNullOrEmpty(searchString))
    {
        items = items.Where(item => item.Name.Contains(searchString));
    }
    return View(items);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:25:22