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

用Html传递另一个查询字符串param。BeginForm和FormMethod。收到

  •  1
  • J86  · 技术社区  · 8 年前

    我在ASP工作。NET MVC 5。我有一个产品列表,想按名称筛选它们。我创建了一个位于产品列表上方的小表单。

    代码

    这是剃须刀表

    @using (Html.BeginForm("Page", "Inventory", routeValues: new { showDeleted = false }, method: FormMethod.Get))
    {
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            @Html.LabelFor(model => model.Search.SearchTerm, new { @class = "form-label" })
            <div class="controls">
              @Html.EditorFor(m => m.Search.SearchTerm, new { htmlAttributes = new { @class = "form-control" } })
              @Html.ValidationMessageFor(model => model.Search.SearchTerm, "", new { @class = "text-danger" })
            </div>
          </div>
        </div>
        <div class="col-md-12">
          <button type="submit" class="btn btn-primary pull-right filter">Filter Results</button>
        </div>
      </div>
    }
    

    这是它应该使用的控制器方法:

    public ActionResult Page(SearchViewModel search, bool showDeleted, int page = 1)
    {
      var viewModel = _productService.GetPagedProducts(search, showDeleted, page);
      return View(viewModel);
    }
    

    提交带有任何搜索词的过滤器会破坏应用程序,并出现以下错误:

    参数字典包含非null类型“System”的参数“showDeleted”的null条目。布尔“for method”系统。网状物Mvc。ActionResult页面(Proj.ViewModels.Shared.SearchViewModel,Boolean,Int32)“在”项目中。控制器。库存控制器'。可选参数必须是引用类型、可为null的类型或声明为可选参数。

    我知道它为什么会失败,因为 showDeleted 我设置的是被忽视和扔掉!但我不知道如何解决这个问题。

    1 回复  |  直到 8 年前
        1
  •  2
  •   Shyju    8 年前

    您的代码将生成正确的表单操作url,其中包含 showDeleted 参数

    action="/Inventory/Page?showDeleted=False"
    

    但既然你在使用 作为表单提交方法,当表单提交时,浏览器将从表单中读取输入元素值,并构建查询字符串并将其附加到表单操作url。这将覆盖您在那里已有的查询字符串。

    如果你想用querystring发送这个 GET 作为form方法,表单中应该有一个同名的输入元素

    @using (Html.BeginForm("Page", "Inventory", FormMethod.Get))
    {
        @Html.EditorFor(m => m.Search.SearchTerm, 
                              new { htmlAttributes = new { @class = "form-control" } })
        <input type="hidden" name="showDeleted" value="false" />
        <button type="submit" class="btn btn-primary filter">Filter Results</button>
    
    }
    
    推荐文章