繁体   English   中英

多个参数ASP Net MVC 4

[英]Multiple params asp net mvc 4

我已经有一个城市参数,代表要在数据库上搜索的城市名称,当我执行mysite / List?city = mycityname时,一切工作正常,但是我想做的是我也想做一个按名字搜索和城市名称示例List?city = 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);
    }

你可以这样写

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

您可以进行一些条件查询,例如

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

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM