【发布时间】:2022-01-10 22:31:31
【问题描述】:
我收到以下错误:
System.NullReferenceException: '对象引用未设置为对象的实例。'
Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get 返回 null。
我正在尝试将 Id 从视图传递到控制器 HttpPost 操作方法。
这是我的代码:
控制器:
public class HomeController : Controller
{
...
[Authorize]
public IActionResult List()
{
var currentUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
var currentCars = db.Cars.Where(x => x.CreatedByUserId == currentUserId)
.Select( x => new CarsListViewModel
{
CarId = x.Id,
CreatedOn = x.CreatedOn,
CreatedByUserId = x.CreatedByUserId,
CreatedByUserName = x.CreatedByUserName,
Firstname = x.PrimaryData.Firstname,
Lastname = x.PrimaryData.Lastname
}).
ToList();
return View(currentCars);
}
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public IActionResult List(int carId)
{
var Car = db.Cars.FirstOrDefault(x => x.Id == carId);
db.Cars.Remove(Car);
db.SaveChanges();
return View();
}
视图模型:
public class CarListViewModel
{
public int CarId { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedByUserId { get; set; }
public string CreatedByUserName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
}
查看(List.cshtml):
@model List<CVBuilder.ViewModels.CarListViewModel>
@{
ViewData["Title"] = "List of current cars";
}
<div class="col-md-10 offset-md-1">
<table class="table table-hover text-nowrap">
<thead>
...
</thead>
<tbody>
@for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>@Model[i].CreatedOn</td>
<td>@Model[i].CreatedByUserName</td>
<td>@Model[i].Firstname</td>
<td>@Model[i].Lastname</td>
<td>
<form method="post">
<input type="hidden" name="carId" value="@Model[i].CarId" />
<button type="submit" class="btn btn-danger btn-sm">Delete</button>
</form>
</td>
</tr>
}
</tbody>
</table>
@if (Model.Count == 0)
{
<div class="text-center"><p>No cars created.</p></div>
}
</div>
【问题讨论】:
-
Post方法中
Car变量的值是多少?我怀疑carId的值是 0 -
您应该使用类似这样的方式更改按钮声明。
<button type="button" onclick="location.href='@Url.Action("ActionName", "ControllerName",Model[i].CarId)'">。无需使用隐藏字段传递值。 -
carId 在 Post 方法中不为 0。它得到了正确的 ID,但我在视图中得到了 NullReferenceException。 Visual Studio 指向 for 循环和 line value="@Model[i].CarId" 为 null。
-
请告诉我哪一行?
-
View 显示正确的 CarId。顺便说一句,我更改了 Post 方法
return RedirectToAction("List"),现在一切正常。非常感谢。
标签: c# asp.net entity-framework