【发布时间】:2020-04-27 16:59:33
【问题描述】:
我目前正在构建一个 MVC 应用程序,我正在尝试根据选定的下拉列表显示汽车列表。我不希望用户必须选择多个下拉列表进行搜索,我希望代码能够通过下拉列表的任意组合进行搜索。我开始用 If else 语句编写代码,但我认为这不是最佳实践,所以我做了一些研究并找到了一种不同的方法来过滤我的结果。我遇到的问题是我在模型中得到了一个空值。
这是我的模特
public partial class Car
{
private Ignition_Hub_DBEntities Context;
public IQueryable<Car> GetProducts(Car searchModel)
{
var result = Context.Cars.AsQueryable();
if (searchModel != null)
{
if (searchModel.CarLotID.HasValue)
result = result.Where(x => x.CarLotID == searchModel.CarLotID);
if (searchModel.Available.HasValue)
result = result.Where(x => x.Available == searchModel.Available);
if (searchModel.ModelID.HasValue)
result = result.Where(x => x.ModelID == searchModel.ModelID);
if (searchModel.Model.MakeID.HasValue)
return result;
result = result.Where(x => x.Model.MakeID == searchModel.Model.MakeID);
return result;
}
return result;
}
public Car()
{
Context = new Ignition_Hub_DBEntities();
}
public int? CarID { get; set; }
public string Year { get; set; }
public string Notes { get; set; }
public bool? Available { get; set; }
public string VinNumber { get; set; }
public int? CarLotID { get; set; }
public int? ModelID { get; set; }
public virtual Model Model { get; set; }
public virtual CarLot CarLot { get; set; }
}
这是我的控制器
public ActionResult DisplaySearchResults(Car searchModel)
{
var business = new Car();
var model = business.GetProducts(searchModel);
return PartialView("_Index", model);
}
现在我在if (searchModel.Model.MakeID.HasValue) 上收到错误消息
错误是'Object reference not set to an instance of an object.'
在此先感谢您的帮助!如果有更好的方法来实现这一点,请指教。谢谢!
【问题讨论】:
标签: c# asp.net .net asp.net-mvc entity-framework