具有多个表单的ASP.NET MVC 5 Get方法持久化搜索URL查询

时间:2016-12-08 23:24:04

标签: asp.net asp.net-mvc razor asp.net-mvc-5.2

我在一个剃刀视图中有两个表单,它们调用相同的控制器操作。

如果我通过搜索输入过滤搜索结果,则网址会保留查询参数和值,例如?SearmTerm = Value ,这样可以正常工作。

但是,如果我想深入了解其他过滤器,例如我从下拉列表中选择一个选项,然后点击以另一种形式包装的搜索按钮,删除?SearmTerm = Value 并添加新的查询参数 CategoryId = 12

我知道如果我使用单个表单,搜索参数和过滤器会在url查询字符串中保留。有可能用多种形式做到这一点吗?我希望它像http://www.carsales.com.au/一样工作,您可以使用搜索按钮添加任意数量的过滤器,查询网址字符串会保留所有参数及其值。

请查看我目前的代码。

Index.cshtml

<div id="filterAccordion" class="body" aria-multiselectable="true">
<ul>
    <li>
        <div class="title" role="tab" id="Location">
            Category
            <a data-toggle="collapse" data-icon="filterIcon" data-parent="#filterAccordion" href="#filterCollapseOne" aria-controls="filterCollapseOne">
                <span class="icon icon-keyboard_arrow_down"></span>
            </a>
        </div>
        <div id="filterCollapseOne" class="collapse content" role="tabpanel" aria-labelledby="Location">
            @using (Html.BeginForm("Index", "Directory", FormMethod.Get))
            {
                @Html.DropDownListFor(model => model.CategoryId, @Model.DirectoryCategories, "Select Category", htmlAttributes: new { @class = "custom-select form control" })

                <div class="form-group">
                    <input type="submit" class="btn search-btn btn-primary" value="Search" />
                </div>                      
            }
        </div>
    </li>
</ul>

<div class="search-bar">
@using (@Html.BeginForm("Index", "Directory", FormMethod.Get))
{
    @Html.TextBoxFor(d => d.SearchTerm, new { @class = "form-control", placeholder = "Search Directory"})
    <button type="submit" class="search-btn"></button>
}
</div>

查看模型

public class DirectoryIndexViewModel
{
   public List<Models.Directory> ActiveDirectories { get; set; }
   public IEnumerable<SelectListItem> DirectoryCategories { get; set; }
   public string SearchTerm { get; set; }
   public string SortBy { get; set; }
   public int CategoryId { get; set; }
}

DirectoryController

[HttpGet]
public ActionResult Index(DirectoryIndexViewModel model)
{
  var query = _directoryRepository.GetAllActiveDirectories();
  var categories =    _selectListService.GetDirectoryCategories(model.CategoryId);

  var searchTerm = model.SearchTerm;

  if (!String.IsNullOrEmpty(searchTerm))
  {
      query = query.Where(d => d.Name.ToUpper().Contains(searchTerm.ToUpper()));
  }

  query = query.OrderByDescending(d => d.IsFeatured);

  return View(new DirectoryIndexViewModel
  {
      ActiveDirectories = query.ToList(),
      DirectoryCategories = categories == null ? null : categories,
      SearchTerm = searchTerm,
      CategoryId = model.CategoryId
  });
}

0 个答案:

没有答案