Multiple params asp net mvc 4

本文关键字:mvc net asp params Multiple | 更新日期: 2023-09-27 18:12:10

我已经有一个城市参数,它代表一个城市名称,我将搜索我的数据库,一切都工作得很好,当我做mysite/List?city=mycityname,但我想做的是,我还想按名字和cityname示例进行搜索列表?城市= mycityname& firstName = myfirstname。我该怎么做呢?这是我对城市的查询,我还添加了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);
    }

Multiple params asp net mvc 4

您可以创建一些条件查询,例如

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计算的搜索条件

你可以这样写

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

看一下下面的代码:

    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);
    }