我收到以下錯誤:
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>
uj5u.com熱心網友回復:
試試看:
public IActionResult List([FromForm]int carId){
// return View(); remove
return RedirectToAction("List")
}
uj5u.com熱心網友回復:
您可以嘗試將特定模型 ID 從視圖傳遞到 MVC 中的控制器
<button href="@Url.Action("List", "ControllerName", new { carId = @Model[i].CarId},null)" button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/378630.html
