MVC:使用以下代码通过多个参数筛选表
本文关键字:参数 筛选 代码 MVC | 更新日期: 2023-09-27 18:01:16
我使用的是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);
}
现在,问题是我必须用数据填充品牌,类别和语言文本框,否则当我应该能够按我想要的任何内容过滤时,它将无法过滤,无论是单独的品牌还是品牌和语言,等等。
仅使用用户提供的内容并避免未传递数据的最有效方法是什么?
可以通过以下几个步骤构造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);
结合Alex的回答,您需要将参数设置为可空和默认值:
public ActionResult Index(string brand_name = null, string category_name = null,
string language_name = null, int? page = null)
这样,如果你没有传递,例如,brand_name
进入方法,那么它将自动设置为null
,但是你也可能想要在你的代码中null检查,这就是Alex的答案派上用场的地方