使用标签助手调用控制器,包括来自 asp.net core mvc 中搜索栏的数据

Posted

技术标签:

【中文标题】使用标签助手调用控制器,包括来自 asp.net core mvc 中搜索栏的数据【英文标题】:Call controller with tag helpers including data from search bar in asp.net core mvc 【发布时间】:2019-06-13 23:03:09 【问题描述】:

我对前端有点新,所以请耐心等待。

我试图用 asp.net core 2.2 MVC 创建一个表单,为了调用大家在线建议使用 ajax,但我想使用新的标签助手。 这是我的代码(控制器 user 与我所在的控制器不同)

       <form method="get" asp-area="" asp-controller="User" asp-action="UserByUsername">
           <input id="userName" type="text" placeholder="Search.." name="1">
           <button type="submit" value="userName">a</button>
       </form>

按钮调用与 ?1=value 相同的 url

但我想调用标签中指定的控制器和操作,参数作为字符串 user/userbyusername/whatusertype

的一部分

我应该改变什么才能让它工作?提前致谢!

更新 ----------------------

我通过 asp-route-value 传递参数,但它传递的是“userName”而不是下面的 texboxid“userName”的值

   <form method="get"asp-route-username="userName" asp-area="" asp-controller="User" asp-action="UserByUsername">
        <input id="userName" type="text" placeholder="Search..">
        <button type="submit" value="userName">a</button>
    </form>

我怎样才能传递那个值?

【问题讨论】:

请使用asp-route-id传递参数 有效!非常感谢!但是我如何将输入中的值传递给标签?我使用了输入的 id 但没有传递它。 我把 asp-route-username="userName", (与 id 相同)但没有传递文本框的值 你必须在路由配置中处理这个 是的,我已经这样做了,但我无法将输入的值传递给 asp-route-value 【参考方案1】:

首先写下你的form,具体如下:

<form method="post" asp-area="" asp-controller="User" asp-action="UserByUserName">
        <input name="userName" type="text" placeholder="Search..">
        <button type="submit">Submit</button>
</form>

现在在你的控制器方法中:

[HttpPost]
public IActionResult UserByUserName(string userName)

    // do whatever you want to do with `userName`

    return View();

这里我使用了post 方法。您还可以使用代码中显示的get 方法。为此,只需将method="post" 替换为method="get" 并将[HttpPost] 替换为[HttpGet]

现在一切正常。

【讨论】:

以上是关于使用标签助手调用控制器,包括来自 asp.net core mvc 中搜索栏的数据的主要内容,如果未能解决你的问题,请参考以下文章

在 asp.net 核心中使用输入标签助手 - “值”为空

用asp.net做一个简单调用+-×÷的控制台程序,定义一个math类,包括plus,minus

asp.net 有条件地禁用标签助手(textarea)

asp.net core 选择标签助手

asp.net核心中的部分标签助手和HTML助手有啥区别?

示例 AJAX 回调到 ASP.NET Core Razor 页面