【发布时间】: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