首页 > 解决方案 > Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get 返回 null

问题描述

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

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

谢谢你的帮助

汽车控制器.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);
    }
}

数据库文件

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;
    }
}

汽车.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; }
}

详细信息.cshtml

@model Car

Make: @Model.Make

Year: @Model.Year

Color: @Model.Color

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

解决方案


比较有问题string。您的 URL 是car/details/tesla,并且您将在数据集中获得它的tesla位置。MakerTesla

所以,你必须注意两点

  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用于过滤记录。


推荐阅读