2013-05-06 65 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); 
    }