2013-05-06 55 views
0

我已经有一个城市参数代表我将在我的数据库上搜索的城市名称,当我做mysite/List?city = mycityname时,一切正常,但我正在尝试做什么是,我还想通过名字搜索结合城市名称示例 列表?city = mycityname & firstName = myfirstname。我怎样才能做到这一点 ?这里是我对城市的查询,我也添加了firstname参数,但我并不真正知道如何添加它,因此它会过滤两者。多参数asp网络mvc 4

public string CurrentFirstName { get; set; }

public ViewResult List(string city, string firstName, int page = 1) 
    { 
     UsersListViewModel model = new UsersListViewModel 
     { 
      Users = repository.Userss 
      .Where(p =>city == null || p.CityName == city) 
      .OrderBy(p => p.UsersId) 
      .Skip((page - 1) * PageSize) 
      .Take(PageSize), 
      PagingInfo = new PagingInfo 
      { 
       CurrentPage = page, 
       UsersPerPage = PageSize, 
       TotalUsers = repository.Userss.Count() 
      }, 
      CurrentCity = city 
      // CurrentFirstName = firstName 
     }; 
     return View(model); 
    } 

回答

1

你可以做一些条件查询的建筑一样,

public ViewResult List(string city, string firstName, int page = 1) 
{ 
    var query = repository.Userss.Where(p => city == null || p.CityName == city); 
    if (firstName != null) 
     query = query.Where(p => firstName == null || p.FirstName == firstName); 

    var model = new UsersListViewModel 
    { 
     Users = query 
     .OrderBy(p => p.UsersId) 
     .Skip((page - 1) * PageSize) 
     .Take(PageSize), 
     PagingInfo = new PagingInfo 
     { 
      CurrentPage = page, 
      UsersPerPage = PageSize, 
      TotalUsers = repository.Userss.Count() 
     }, 
     CurrentCity = city 
     // CurrentFirstName = firstName 
    }; 
    return View(model); 
} 

注:我想你也应该考虑TotalUsers计算

希望这有助于搜索条件。

1

你可以写这样的事情

Users = repository.Userss 
     .Where(p =>city == null || p.CityName == city) 
     .Where(p=> firstName == null || p.FirstName == firstName) 
     .OrderBy(p => p.UsersId) 
    // rest of your query 
1

看一看到下面的代码:

public ViewResult List(string city, string firstName, int page = 1) 
    { 
     UsersListViewModel model = new UsersListViewModel 
     { 
      Users = repository.Userss 
      .Where((p =>city == null || p.CityName == city) && 
      (p =>firstname == null || p.FirstName == firstName)) 
      .OrderBy(p => p.UsersId) 
      .Skip((page - 1) * PageSize) 
      .Take(PageSize), 
      PagingInfo = new PagingInfo 
      { 
       CurrentPage = page, 
       UsersPerPage = PageSize, 
       TotalUsers = repository.Userss.Count() 
      }, 
      CurrentCity = city 
      CurrentFirstName = firstName 
     }; 
     return View(model); 
    }