ASP.NET MVC中如何将CaTrúc下拉列表加入Linq多条件搜索?
给ASP.NET MVC报表添加CaTrúc下拉筛选的Linq集成方案
步骤1:修改控制器Action参数
在Index方法的参数列表中添加CaTrúc对应的筛选参数,参数类型根据数据库中CaTrúc字段的实际类型调整(示例用字符串类型):
public ActionResult Index(DateTime? start, DateTime? end, string caTruc)
步骤2:集成Linq的Where筛选逻辑
在原有日期筛选的基础上,添加CaTrúc的条件判断,需处理用户未选择下拉选项的情况(此时不应用该筛选):
var result = db.View_XeQuaTramReport .Where(r => r.NgayCa >= strStart && r.NgayCa <= strEnd) // 新增CaTrúc筛选:如果筛选值为空则跳过,否则匹配对应值 .Where(r => string.IsNullOrEmpty(caTruc) || r.CaTruc == caTruc) .GroupBy(r => new { r.LoaiVe, r.LoaiXe, r.Phi }) .Select(g => new XeQuaTramDTO { LoaiVe = g.Key.LoaiVe, LoaiXe = g.Key.LoaiXe, Phi = g.Key.Phi, TongPhi = g.Sum(r => r.Phi), TongXe = g.Count() }) .OrderBy(r => new { r.LoaiVe, r.LoaiXe, r.Phi, r.TongPhi, r.TongXe }) .ToList();
如果数据库中CaTrúc是数值类型(比如int),则调整参数和判断逻辑:
// 参数改为可空整数类型 public ActionResult Index(DateTime? start, DateTime? end, int? caTruc) // 筛选逻辑改为 .Where(r => !caTruc.HasValue || r.CaTruc == caTruc.Value)
步骤3:在视图中添加下拉筛选控件
在报表搜索表单里添加CaTrúc下拉列表,可从数据库动态获取选项或硬编码:
动态获取选项(从数据库表读取)
<div class="form-group"> @Html.Label("CaTrúc", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("caTruc", new SelectList(db.CaTrucList.Select(c => new { Value = c.MaCa, Text = c.TenCa }), "Value", "Text"), "全部", new { @class = "form-control" }) </div> </div>
硬编码选项
<div class="form-group"> @Html.Label("CaTrúc", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("caTruc", new List<SelectListItem> { new SelectListItem { Text = "Ca 1", Value = "1" }, new SelectListItem { Text = "Ca 2", Value = "2" }, new SelectListItem { Text = "Ca 3", Value = "3" } }, "全部", new { @class = "form-control" }) </div> </div>
完整修改后的控制器代码
public DongphuocDbContext db = new DongphuocDbContext(); // GET: Report public ActionResult Index(DateTime? start, DateTime? end, string caTruc) { if (start == null || end == null) { return View(); } DateTime strStart = start.Value.Date; DateTime strEnd = end.Value.Date; var result = db.View_XeQuaTramReport .Where(r => r.NgayCa >= strStart && r.NgayCa <= strEnd) .Where(r => string.IsNullOrEmpty(caTruc) || r.CaTruc == caTruc) .GroupBy(r => new { r.LoaiVe, r.LoaiXe, r.Phi }) .Select(g => new XeQuaTramDTO { LoaiVe = g.Key.LoaiVe, LoaiXe = g.Key.LoaiXe, Phi = g.Key.Phi, TongPhi = g.Sum(r => r.Phi), TongXe = g.Count() }) .OrderBy(r => new { r.LoaiVe, r.LoaiXe, r.Phi, r.TongPhi, r.TongXe }) .ToList(); return View(result); }
内容的提问来源于stack exchange,提问作者Phatt
相关产品推荐
相关产品推荐

