代码之家  ›  专栏  ›  技术社区  ›  ZNAXNOR

FormMethod。使用Html。BeginForm在ASP中出现错误。NET核心MVC

  •  0
  • ZNAXNOR  · 技术社区  · 2 年前

    我正在尝试实现 搜索查询字符串 我的搜索栏。

    遵循 Microsoft documentation: Adding search ,建议使用 Html.BeginForm("action", "controller", FormMethod.Get) 方法,当我得到错误时:

    此页面不起作用

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

    HTTP错误405

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

    localhost:7185/Searchbar__RequestVerificationToken=CfDJ8GCygMwCAINPiWbEfcvWp986TX925YtT_ivBMr4CJ0Cj6g6BDdH6xua1gReYA37rr5ljwc_GCuVXkANiQOt6hJVJpOLr308aqLyyO6ii9fpf6DIbDlkKxYtOHHRN-O5eOxj4ie-TU-uBX2CNp0x4&SearchString=a&__请求验证令牌=CfDJ8GCygMwCAINPiWbEfcvWp986TX925YtT_ivBMr4CJ0Cj6g6BDdH6xua1gReYA37rr5ljwc_GCuVXkANiQOt6hJVJpOLr308aqLyyO6ii9fpf6DIbDlkKxYtOHrN-O5eOxj4ie-TU-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>
    }
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   ZNAXNOR    2 年前

    这是我的解决方案


    • 去除 [HttpPost] 来自控制器动作。
      • 作为使用 FormMethod。收到 具有 BeginForm 将渲染到 <form method="get"> 不能 使用 [HttpPost] 在控制器中,渲染到 <form method="post"> .
    public async Task<IActionResult> Index(string searchString)
    {
        //Code
    }
    
    • 去除 <form> 视图中的元素
      • BeginForm 渲染 <表单> 元素,您现有的 <表单> 标记助手将表现为 子元素 .
      • 即使不遵循此步骤,页面也会进行渲染,但这将导致 搜索查询字符串 行为怪异。
    @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>
    }
    

    非常感谢。