Flood Gravemind
Flood Gravemind

Reputation: 3803

How does the Controller know the Id on DeleteConfirmed in MVC?

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");
        }

Upvotes: 5

Views: 1461

Answers (2)

badr slaoui
badr slaoui

Reputation: 1063

It comes from the form tag ,if you check it you will find that the action is ControllerName/Delete/Id and this is from where the Id comes , the default routing do the job .

Upvotes: 0

WannaCSharp
WannaCSharp

Reputation: 1898

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.

Upvotes: 4

Related Questions