0
我試圖在每個操作之前插入一個斷點,並且我在HttpGet方法中的ClassId值取需要刪除的類的實際(正確)Id時卡住了一點HttpPost方法中的ClassId值與HttpGet方法的ClassId值不匹配,HttpPost中ClassId的Infact值返回null,因此我遇到了對象具有空值的異常錯誤。如果有人能夠承認我可以消除這種錯誤,那將是非常好的。謝謝。下面分別是控制器的代碼和相應的視圖。控制器中的HttpPost方法與HttpGet方法不協調
控制器代碼
[HttpGet]
public IActionResult Delete(int ClassId)
{
return View(db.Class.Include(x => x.Student).First(c => c.ClassId == ClassId));
}
[ActionName("Delete")]
[HttpPost]
public IActionResult DeletePost(int ClassId)
{
var r = db.Class.First(a => a.ClassId == ClassId);
var student = r.StudentId.ToString();
db.Remove(r);
db.SaveChanges();
return RedirectToAction("Details", "Student", new { id = student });
}
查看代碼
@model DemoProject.Models.Class
@{
ViewData["Title"] = "Delete Class";
}
<h3>Are you sure you want to delete this?</h3>
<div>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.ClassName)
</dt>
<dd>
@Html.DisplayFor(model => model.ClassName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Text)
</dt>
<dd>
@Html.DisplayFor(model => model.Text)
</dd>
</dl>
<form asp-action="Delete">
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-danger" />
<div class="row">
<a asp-action="Details" asp-controller="Student" asp-route-id="@Model.Student.StudentId">Back</a>
</div>
</div>
</form>
</div>
你可以將代碼發佈到你的視圖嗎? –
@CoreySmith我剛剛發佈了它 – Priyanshu
你似乎沒有將ID從你的表單傳遞給post方法。使用隱藏字段或類似內容。 –