MVC:使用以下代码

时间:2015-07-06 13:03:16

标签: c# asp.net-mvc model-view-controller lambda

我正在使用PagedList.Mvc对表格进行分页,并在表格标题的顶部添加了三个过滤器。一个用于品牌,一个用于一个类别,另一个用于语言。以下代码有效......

public ActionResult Index(string brand_name, string category_name, string language_name, 
                            int? page)
        {

            ViewData["brand_name"] = brand_name;
            ViewData["category_name"] = category_name;
            ViewData["language_name"] = language_name;

                    IPagedList<Material> onePageOfProducts = db.Materials
                    .Select(i => new Material
                    {
                        Brand = i.Brand,
                        Category = i.Category,
                        Language = i.Language,
                        Bco = i.Bco,
                        MaterialCod = i.MaterialCod,
                        Derivation = i.Derivation,
                        Artwork = i.Artwork,
                        BcoDelivery = i.BcoDelivery,
                        MaterialId = i.MaterialId
                    })
                    .Where(p =>
                        p.Brand.ToLower().Contains(brand_name.ToLower()) &&
                        p.Category.ToLower().Contains(category_name.ToLower()) &&
                        p.Language.ToLower().Contains(language_name.ToLower())
                    )
                    .OrderBy(i => i.MaterialCod)
                    .ToPagedList<Material>(pageNumber, defaultPageSize);

                return View("Index", onePageOfProducts);
         }

现在,问题是我必须用数据填充品牌,类别和语言文本框,否则当 能够按任何方式过滤时,它不会过滤我想要,无论是品牌,品牌和语言,等等。

仅使用用户提供的内容进行过滤的最有效方法是什么?避免数据未通过?

2 个答案:

答案 0 :(得分:1)

您可以通过以下几个步骤构建IQueryable:

var query = db.Materials
    .Select(i => new Material
    {
        Brand = i.Brand,
        Category = i.Category,
        Language = i.Language,
        Bco = i.Bco,
        MaterialCod = i.MaterialCod,
        Derivation = i.Derivation,
        Artwork = i.Artwork,
        BcoDelivery = i.BcoDelivery,
        MaterialId = i.MaterialId
     });

if (brand_name != null)
    query = query.Where(p => p.Brand.ToLower().Contains(brand_name.ToLower());

if (category_name!= null)
    query = query.Where(p => p.Category.ToLower().Contains(category_name.ToLower());

if (language_name!= null)
    query = query.Where(p => p.Language.ToLower().Contains(language_name.ToLower());

IPagedList<Material> onePageOfProducts = query
    .OrderBy(i => i.MaterialCod)
    .ToPagedList<Material>(pageNumber, defaultPageSize);

答案 1 :(得分:1)

结合Alex的回答,您需要使参数可为空并且默认为:

public ActionResult Index(string brand_name = null, string category_name = null, 
                          string language_name = null, int? page = null)

这样,如果你没有将brand_name传递给方法,那么它将自动设置为null,但你也可能想要检查你的代码,这是Alex的答案派上用场的方式