动作方法不适用于asp.net MVC中的[HttpPost]属性

问题描述 投票:1回答:1

[使用asp.net MVC 5删除Razor Engine中的数据,我编写了可以正常工作的代码。但是,我想给它[HttpPost]属性,但是如果我添加它,该操作将不起作用。

有人可以帮我吗?有什么问题?

我只有一个名为delete的动作,不需要具有Delete属性的另一个[HttpGet]动作。我该如何解决?

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

管理员控制器

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>
asp.net asp.net-mvc model compiler-errors asp.net-mvc-5
1个回答
1
投票

[HttpPost]属性标记您的方法

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

并更改视图以使用表单而不是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>
}

如果在删除之前还需要确认消息,请添加以下jquery脚本(如果用户单击Cancel或关闭对话框而不单击OK,则表单提交将被取消]

$('form').submit(function() {
  return confirm('Are you sure to delete it?');
})
© www.soinside.com 2019 - 2024. All rights reserved.