Action method didn't worked with [HttpPost] at

2019-08-15 05:19发布

问题:

To delete data in asp.net mvc 5 with Razor Engine , I wrote these code that works fine . I want to give it [HttpPost] attribute , but if I add that , action didn't worked . Could anyone help me what's the problem ? I have just one action named delete , I don't need another Delete action with [HttpGet] attribute . How can I fix it ?

Repositories.cs

public bool Delete(int id, bool autoSave = true)
    {
        try
        {
            var entity = db.Carousels.Find(id);
            db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
            if (autoSave)
                return Convert.ToBoolean(db.SaveChanges());
            else
                return false;
        }
        catch
        {
            return false;
        }
    }

Admin controller

public ActionResult DeleteCarousel(int id)
    {
        CarouselRepositories blCarousel = new CarouselRepositories();
        blCarousel.Delete(id);
        return View("ShowCarousel", blCarousel.Select());
    }

ShowCarousel.cshtml

@model IEnumerable<NP1.Models.Carousel>

@{
ViewBag.Title = "ShowCarousel";
Layout = "~/Views/Admin/AdminLayout.cshtml";
}


 <table class="table">
 <tr>
    <th>
        @Html.DisplayNameFor(model => model.CarouselSubject)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.CarouselInfo)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.CarouselImage)
    </th>
    <th></th>
 </tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.CarouselSubject)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.CarouselInfo)
    </td>
    <td>
        @*@Html.DisplayFor(modelItem => item.CarouselImage)*@
        <img style="width:300px; height:200px;" src="~/Images/Carousel/@item.CarouselImage" />
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.CarouselID }) |
        @Html.ActionLink("Delete", "DeleteCarousel", new { id = item.CarouselID })
    </td>
</tr>
 }

</table>

回答1:

Mark you method with the [HttpPost] attribute

[HttpPost]
public ActionResult DeleteCarousel(int id)
{
  ....
}

and change the view to use a form rather than an ActionLink()

@foreach (var item in Model)
{
  <tr>
    <td>@Html.DisplayFor(m => item.CarouselSubject)</td>
    ....
    <td>
        @using (Html.BeginForm("DeleteCarousel", "yourControllerName", new { id = item.CarouselID }, FormMethod.Post))
        {
          <input type="submit" value="Delete" /> // style it look like a link if you want
        }
    </td>
  </tr>
}

If you also want a confirmation message before deleting, add the following jquery script (the form submit will be cancelled if the user clicks Cancel or closes the dialog without clicking OK)

$('form').submit(function() {
  return confirm('Are you sure to delete it?');
})