c# - 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
解决方案
比较有问题string
。您的 URL 是car/details/tesla
,并且您将在数据集中获得它的tesla
位置。Maker
Tesla
所以,你必须注意两点
- 检查您的
car
数据库是否为空或不基于make
. - 忽略大小写敏感,同时进行字符串比较。
你的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
用于过滤记录。
推荐阅读
- python - Python ctypes结构:可以在不定义类/内联的情况下制作吗?
- reactjs - 状态更新不会在 ReactJS 中重新渲染组件
- wordpress - contactform7 如何附加任何类型的文件
- qgis - 用行号和列号索引网格?
- c - 什么应该 printf("%.15e", 1e23); 打印?
- reactjs - Material UI makeStyles 在其他类下时覆盖其中的类属性
- google-cloud-platform - Cloud Run 警告日志:容器调用 exit(3)
- python - 如何将私钥转换为base64格式?
- javascript - 如何从 vue3 中的 ref 对象获取数据属性
- python - 传感器数据采样频率不匹配