I am currently building an MVC application and I am trying to display a list of cars based on the selected dropdown. I dont want the user to have to select multiple dropdown to search, I want the code to be able to search by any combination of the dropdowns. I started wrinting the code with If else statements but I didnt think this was the best practice so I did some research and found a different way to filter my results. The issue that I am having is that the I am getting a null value in a Model.
This is my model
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; }
}
This is my controller
public ActionResult DisplaySearchResults(Car searchModel)
{
var business = new Car();
var model = business.GetProducts(searchModel);
return PartialView("_Index", model);
}
Right now I get an error on if (searchModel.Model.MakeID.HasValue)
the error is 'Object reference not set to an instance of an object.'
Thanks in advance for the help! If there is a better way to achieve this, please advise. Thank you!