Hi can someone please explain how the default delete method generated by Visual Studio work. I am confused because when you Post DeleteConfirmed
the model Id
is passed back to controller. But in the View there is no Id
field generated not even in a hidden field so how come Id
is not lost/reset on Post? How does the Controller know the Id
?
View
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>SellersQuery</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Name)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Manufacturer)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Manufacturer)
</div>
</fieldset>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "Index")
</p>
}
Controller
public ActionResult Delete(int id = 0)
{
SellersQuery sellersquery = db.SellerQuerySet.Find(id);
if (sellersquery == null)
{
return HttpNotFound();
}
return View(sellersquery);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
SellersQuery sellersquery = db.SellerQuerySet.Find(id);
db.SellerQuerySet.Remove(sellersquery);
db.SaveChanges();
return RedirectToAction("Index");
}
This even works without parameters, so at that point, you might wonder how in the world a Controller knows exactly which of your Views to return for a specific Action. The answer is something called View Discovery - a process where ASP.NET MVC will try to guess which View to use, without forcing you to specify it.
MVC by default will find a View that matches the name of the Controller Action itself (it actually searches both the Views and Shared folders to find a cooresponding View that matches). Additionally, Index is always the "default" Controller Action (and View).
In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.
It's a url path parameter. The name id is used to match against a parameter on the controller action with the same name. You could use any name you, like you have in the second example. You can specify in route actions where the value id should come from, the body, url etc.
Your GET Delete
URL is probably something like this /Controller/Action/Id
.
So even if you don't have an ID
field in your form, the ID
in the URL is mapped to the ID
in the method parameter when you submit the form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With