Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>.Model.get 返回 null

时间:2021-02-12 04:12:10

标签: c# asp.net-core-mvc

我可以看到汽车列表及其信息,但我想通过键入car/details/tesla来查看个别汽车的详细信息。我将字符串类型的 make 作为参数传递给 CarController 类中的详细信息操作方法,但在检查时不断收到空错误。

<块引用>

System.NullReferenceException: '未将对象引用设置为对象的实例。'
Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get 返回 null。

感谢您的帮助

CarController.cs

public class CarController : Controller
{
    public IActionResult List()
    {
        List<Car> cars = DB.GetCars();
        return View(cars);
    }

    public IActionResult Detail(string make)
    {
        Car car = DB.GetCar(make);
        return View(car);
    }
}

DB.cs

public class DB
{
    public static List<Car> GetCars()
    {
        List<Car> cars = new List<Car>()
        {
            new Car()
            {
                VIN = 12321,
                Make = "Toyota",
                Model = "Camry",
                Year = 2009,
                Color = "Black",
                Price = 32000
            },
            new Car()
            {
                VIN = 12323,
                Make = "Nissan",
                Model = "Altima",
                Year = 2020,
                Color = "Red",
                Price = 45000
            },
            new Car()
            {
                VIN = 12325,
                Make = "Tesla",
                Model = "Model 3",
                Year = 2021,
                Color = "Black",
                Price = 86000
            },
        };

        return cars;
    }

    public static Car GetCar(string make)
    {
        List<Car> cars = DB.GetCars();

        foreach (Car car in cars)
        {
            if(car.Make == make)
            {
                return car; 
            }
        }

        return null;
    }
}

Car.cs

public class Car
{
    public int VIN { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }
    public string Color { get; set; }
    public decimal Price { get; set; }
}

Details.cshtml

@model Car

Make: @Model.Make

Year: @Model.Year

Color: @Model.Color

1 个答案:

答案 0 :(得分:0)

string 比较中存在问题。您的 URL 是 car/details/tesla 并且您将 tesla 作为 Maker 而在您的数据集中它是 Tesla

所以,你必须在意两点

  1. 根据 car 检查您的 make 数据库是否为空。
  2. 忽略大小写敏感,同时进行字符串比较。

您的 GetCar() 方法应该遵循。

public static Car GetCar(string make)
{
    if(string.IsNullOrEmpty(make)) return null;
    
    var cars = DB.GetCars()?.Where(c = c.Make?.Equals(make, StringComparison.InvariantCultureIgnoreCase) == true)?.ToList();

    return cars;
}

注意:

我没有使用 forEach,而是使用 LINQ 来过滤记录。

相关问题