【发布时间】: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