【问题标题】:Passing another query string param with Html.BeginForm and FormMethod.Get使用 Html.BeginForm 和 FormMethod.Get 传递另一个查询字符串参数
【发布时间】:2018-04-19 23:14:39
【问题描述】:

背景

我正在使用 ASP.NET MVC 5。我有一个产品列表并希望按名称过滤它们。我创建了一个位于产品列表上方的小表单。

代码

这是 Razor 表单

@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);
}

使用任何搜索词提交过滤器都会破坏应用程序并给出以下错误:

参数字典包含方法“System.Web.Mvc.ActionResult Page(Proj.ViewModels.Shared.SearchViewModel, Boolean, Int32)”的不可为空类型“System.Boolean”的参数“showDeleted”的空条目在“Proj.Controllers.InventoryController”中。可选参数必须是引用类型、可空类型或声明为可选参数。

我知道它为什么会失败,这是因为我设置的 showDeleted 被忽略并丢弃了!但我不知道如何解决这个问题。

【问题讨论】:

  • 我觉得隐藏字段可以帮到你,@Html.Hidden("showDeleted", false)
  • 谢谢@lyz,我知道现在该做什么了。 :)
  • 为该方法创建一个特定路由 - url: "Inventory/Page/{showDeleted} 以便将其添加为路由值,而不是查询字符串,然后您就不需要隐藏输入

标签: c# asp.net-mvc forms razor


【解决方案1】:

您的代码将使用showDeleted 参数的查询字符串生成正确的表单操作网址

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

但是由于您使用 GET 作为表单提交方法,当提交表单时,浏览器将从表单中读取输入元素值并构建查询字符串并将其附加到表单操作 url .这将覆盖您现有的查询字符串。

如果你想用GET作为表单方法在查询字符串中发送这个,你应该在表单中有一个同名的输入元素

@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>

}

【讨论】:

  • 这是唯一的方法吗?为什么我的routeValues 被抛弃了?
  • 因为您正在使用 GET 进行表单提交,这将使用表单输入元素覆盖查询字符串项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 2019-12-09
相关资源
最近更新 更多