【问题标题】:Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>.Model.get returned nullMicrosoft.AspNetCore.Mvc.Razor.RazorPage<TModel>.Model.get 返回 null
【发布时间】:2021-02-12 13:40:28
【问题描述】:

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

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

【问题讨论】:

  • 你应该在调用View( car )之前检查if( car == null )

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


【解决方案1】:

string比较有问题。你的 URL 是 car/details/tesla 并且你得到 tesla 作为 Maker 在你的数据集中它是 Tesla

所以,你一定要注意两点

  1. 根据make检查您的car数据库是否为空。
  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 来过滤记录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    相关资源
    最近更新 更多