Rectangle 27 0

c How to make edit and delete POST Request in same page in my ASP.Net MVC 5 application?


@Html.Partial("_SmallButtonPartial",
   new SmallButtonViewModel
   {
       Action = "Delete",
       ButtonType = "btn-danger",
       Glyph = "trash",
       Text = "Delete button",
       ResumeId = Model.ResumeId,
   })
@using(Html.BeginForm("delete", "your controller name", FormMethod.Post, new { @class="delete-form" }))
{
    <input type="hidden" name="ResumeId" value="@Model.ResumeId" />
    <button type="submit" class="btn btn-danger">
        <span class="glyphicon glyphicon-trash"></span>
        Delete
    </button>
}
[HttpPost]
public ActionResult Delete(int? resumeId)
{
    var r = _context.Resumes.Where(c => c.ResumeId == resumeId);
    _context.Resumes.RemoveRange(r);
    _context.SaveChanges();
    return RedirectToAction("ResumeCenter");
}

Any other actions, like "view" or "edit", would still just be GET requests, which you can leave as anchors, or use forms with the method set to GET (the end result is the same).

If you can tell me in one or two lines, Why I should always have delete httppost. I never understood it conceptually.

Once you add that attribute, any attempts to issue a GET request to that action will result in a 404 (Not Found) response.

So, I should have HTTPPost for delete only, Edit and Details are fine with GET?

The idea behind "we should never have a "GET" Request for Deleting and Editing" is that GET requests should be idempotent, which (put more simply) means nothing should change as a result of making the request. Your Edit and Details are just requests to load either a read-only view (for Details) or to load a form for making changes (for Edit). The Edit view itself would still POST it's form.

The idea is that I should be able to GET the same resource one time or 1000 times, and the result is the same and nothing changed on the server as a result (ignoring things like logging - the resource itself should not change). When you delete something, you are most certainly changing a resource, and calling the same action again will have different results.

Understood. :) So when ever I my action is going to make any change in the resource I should make it as HttpPost

You can have as many forms on a page as you like, as long as they are not nested - this generates a form on each row. I added a class here (delete-form) that you could use to hook into a jQuery event, if you wanted to handle this via AJAX instead of allowing the form to submit.

You would start by making sure the Delete action could only be reached by a POST request, using the HttpPostAttribute:

with something like:

Note