I am following a beginner tutorial on how to make a simple store with asp.net mvc, and in tutorial there is no problem when doing exact same steps.
I am currently trying to perform a basic CRUD operations on my category page, but i am stuck when trying to delete categories. I get not found page because id is null, but i don’t have problem for Edit method when passing the same id parameter.
I was looking for an answer and some people suggest that there might be caching problem, but not sure how to even try to fix that.
Here is my controller for delete operations
// GET-DELETE
public IActionResult Delete(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
Category obj = _db.Category.Find(id);
if (obj == null)
{
return NotFound();
}
return View(obj);
}
//POST-DELETE
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int? id)
{
Category obj = _db.Category.Find(id);
if (id == null)
{
return NotFound();
}
_db.Category.Remove(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
and here is my View
@model RockyWebsite.Models.Category
<form method="post" asp-action="DeletePost">
@Html.HiddenFor(id => id.CategoryId)
<input asp-for="CategoryId" hidden />
<div class="border p-3">
<div class="form-group row">
<h2 class="text-info pl-3">Delete Category</h2>
</div>
<div class="row">
<div class="col-8">
<div class="form-group row">
<div class="col-4">
<label asp-for="CategoryName"></label>
</div>
<div class="col-8">
<input asp-for="CategoryName" disabled class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label asp-for="DisplayOrder"></label>
</div>
<div class="col-8">
<input asp-for="DisplayOrder" disabled class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-4 row">
<div class="col">
<input type="submit" class="btn btn-danger w-100" value="Delete" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-success w-100"><i class="fas fa-sign-out-alt"></i> Back</a>
</div>
</div>
</div>
</div>
<div class="col-4">
@* Keep this empty *@
</div>
</div>
</div>
</form>
Any help or suggestion would be very appreciated, thanks!
3
Answers
add name tag to input, for example :
Alex
You’re using
@Html.HiddenFor(id => id.CategoryId)
(well, you’re actually using the tag-helper syntax too<input asp-for="CategoryId" hidden />
and you should just use one or the other, not both!) in the view which will create an input withname="CategoryId"
.So, the easiest solution is probably to correct the view and update the parameter name in the controller action for
DeletePost
.View:
Controller:
replace your form tag with this one
and action