FormMethod.Get 与 Html.BeginForm 在 ASP.NET Core MVC 中给出错误

问题描述 投票:0回答:1

我试图为我的搜索栏实现一个搜索查询字符串

按照Microsoft文档:添加搜索,当我收到错误时,它建议在视图中使用

Html.BeginForm("action", "controller", FormMethod.Get)
方法:

此页面无法正常工作

如果问题仍然存在,请联系网站所有者。

HTTP 错误 405

我的搜索查询字符串显示:

本地主机:7185 / Searchbar__RequestVerificationToken = CfDJ8GCygMwCAINPiWbEfcvWp986TX925YtT_ivBMr4CJ0Cj6g6BDdH6xua1gReYA37rr5ljwc_GCuVXkANiQOt6hWJVJpOLr308aqLyyO6ii9fpf6DIbDlkK xYtOHHrN-O5eOxj4ie-TU-C-uBX2CNp0x4&SearchString=a&__RequestVerificationToken=CfDJ8GCygMwCAINPiWbEfcvWp986TX925YtT_ivBMr4CJ0Cj6g6BDdH6xua1gReYA37rr5ljwc_GCuVXkaNiQOt6hWJVJpOL r308aqLyyO6ii9fpf6DIbDlkKxYtOHHrN-O5eOxj4ie-TU-C-uBX2CNp0x4

我在控制器中使用了

[ValidateAntiForgeryToken]

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(string searchString)
{
    //Code
}

连同视图中的

@Html.AntiForgeryToken()

@using (Html.BeginForm("Index", "Searchbar", FormMethod.Get))
{
    @Html.AntiForgeryToken()
    <form class="d-flex w-50 ps-lg-5" role="search" asp-controller="Searchbar" asp-action="Index">
        <div class="input-group">
            <input class="form-control shadow-none" value="@TempData["searchString"]" type="search" placeholder="Search" id="text-suggestion" aria-label="Search" name="SearchString"
                   required oninvalid="this.setCustomValidity(' ')" />
            <button class="btn btn-outline-success shadow-none" type="submit" id="search-button"><i class='bx bx-search'></i></button>
        </div>
    </form>
}

谢谢你。

c# html asp.net-core-mvc searchbar antiforgerytoken
1个回答
0
投票

这是我的解决方案


  • 从控制器操作中删除
    [HttpPost]
    • 由于将 FormMethod.GetHtml.BeginForm 一起使用将呈现为
      <form method="get">
      ,因此您不能在呈现为
      [HttpPost]
      的控制器中使用
      <form method="post">
public async Task<IActionResult> Index(string searchString)
{
    //Code
}
  • 从视图中删除
    <form>
    元素
    • Html.BeginForm 呈现
      <form>
      元素时,现有的
      <form>
      标记帮助程序将充当 子元素
    • 即使不执行此步骤,您的页面也会呈现,但这会导致 搜索查询字符串 行为异常。
@using (Html.BeginForm("Index", "Searchbar", FormMethod.Get))
{
    <div class="input-group d-flex ps-lg-5">
        <input class="form-control shadow-none" value="@TempData["searchString"]" type="search" placeholder="Search" id="text-suggestion" aria-label="Search" name="SearchString"
                required oninvalid="this.setCustomValidity(' ')" />
        <button class="btn btn-outline-success shadow-none" type="submit" id="search-button"><i class='bx bx-search'></i></button>
    </div>
}

谢谢你。

© www.soinside.com 2019 - 2024. All rights reserved.