0

error: "Object reference not set to an instance of an object"

I have an error in web application when clicking on button wich have to display cars by the category "Sedan" and "Sports"

Is this error mean that i have to make my properties nullable? (i tried to give '?' symbol to all properties but it doesn't work)

Thanks in advance for help

[Route("Cars/List/")]
[Route("Cars/List/{Category}")]
public ViewResult List(string category)
    {
        string _category = category;
        IEnumerable<Car> cars = null;
        string currCategory = "";

        if (string.IsNullOrEmpty(category)){
            cars = _allCars.Cars.OrderBy(i => i.id);
        }
        else
        {
            if (string.Equals("Sedan", category, StringComparison.OrdinalIgnoreCase))
            {
                cars = _allCars.Cars
                    .Where(i => i.Category.categoryName.Equals("Sedan")) //error appears in this line
                    .OrderBy(i => i.id);
            }
            else
            {
                cars = _allCars.Cars
                    .Where(i=> i.Category.categoryName.Equals("Sports")) //error appears in this line 
                    .OrderBy(i => i.id);                    
            }
            currCategory= _category;
        }

        var carObj = new CarsListViewModel
        {
            allCars = cars,
            currCategory = currCategory,
        };

        ViewBag.Title = "Car's Page";

        return View(carObj);
    }

Category models ->

    public class Category
{
    public int id { get; set; }
    public string categoryName { get; set; }
    public string? desc { get; set; }

    public List<Car> cars { get; set; }
}

Car models ->

    public class Car
{
    public int id { get; set; }
    public string name { get; set; }
    public string shortDesc { get; set; }
    public string longDesc { get; set; }
    public string img { get; set; }
    public ushort price { get; set; }
    public bool isFavourite { get; set; }
    public bool available { get; set; }
    public int categoryID { get; set; }
    public virtual Category Category { get; set; }
}

IAllCars Interface

    public interface IAllCars
{
    IEnumerable<Car> Cars { get; }
    IEnumerable<Car> getFavCars { get; }
    Car getObjectCar(int carId);
}

Map controller route ->

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
name: "categoryFilter",
pattern: "Car/{action}/{category?}",
defaults: new { Controller = "Car", action = "List"});
Alex Hard
  • 35
  • 4

0 Answers0