我正在研究一本mvc书,它显示了搜索按钮的工作原理,它使用相同的名称输入类型文本和输入类型隐藏,我的问题是控制器中的操作如何理解提交时必须使用哪个搜索参数当我们有相同的名字"搜索"用于文本框和隐藏字段
搜索文本框位于" _Layout.cshtml"
@using (Html.BeginForm("Index", "Products", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
{
<div class="form-group">
@Html.TextBox("Search", null, new { @class = "form-control", @placeholder = "Search Products" })
</div>
<button type="submit" class="btn btn-default">Submit</button>
}
和隐藏字段位于&#34; Index.cshtml&#34;
@using (Html.BeginForm("Index", "Products", FormMethod.Get))
{
<label>Filter by category:</label>
@Html.DropDownListFor(vm => vm.Category, Model.CatFilterItems, "All");
<input type="submit" value="Filter" />
<input type="hidden" name="Search" id="Search" value="@Model.Search" />
}
获取参数的动作索引如下所示:
public ActionResult Index(string category, string search)
{
//instantiate a new view model
ProductIndexViewModel viewModel = new ProductIndexViewModel();
//select the products
var products = db.Products.Include(p => p.Category);
//perform the search and save the search string to the viewModel
if (!String.IsNullOrEmpty(search))
{
products = products.Where(p => p.Name.Contains(search) ||
p.Description.Contains(search) ||
p.Category.Name.Contains(search));
viewModel.Search = search;
}
//group search results into categories and count how many items in each category
viewModel.CatsWithCount = from matchingProducts in products
where
matchingProducts.CategoryID != null
group matchingProducts by
matchingProducts.Category.Name into
catGroup
select new CategoryWithCount()
{
CategoryName = catGroup.Key,
ProductCount = catGroup.Count()
};
if (!String.IsNullOrEmpty(category))
{
products = products.Where(p => p.Category.Name == category);
}
viewModel.Products = products;
return View(viewModel);
}
取值