[使用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>
用[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?');
})