[英]Multiple params asp net mvc 4
I already have a city parameter which represent a cityname that I'll search on my DB, everything work well when I do mysite/List?city=mycityname, but what I'm trying to do is that I would also like to do a search by firstname combined with the cityname example List?city=mycityname&firstName=myfirstname. 我已经有一个城市参数,代表要在数据库上搜索的城市名称,当我执行mysite / List?city = mycityname时,一切工作正常,但是我想做的是我也想做一个按名字搜索和城市名称示例List?city = mycityname&firstName = myfirstname。 How can I do this ?
我怎样才能做到这一点 ? Here is my query for city, I also added the firstname parameter but I don't really know how to add it so it'll filter both.
这是我对城市的查询,我也添加了firstname参数,但是我真的不知道如何添加它,因此它将对这两个参数进行过滤。
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);
}
You can write something like this 你可以这样写
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
Have a look into the following code: 看下面的代码:
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);
}
You can do some conditional query building like, 您可以进行一些条件查询,例如
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);
}
Note: i think you should also consider the search criteria on TotalUsers
calculation 注意:我认为您还应该考虑
TotalUsers
计算中的搜索条件
hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.