要使用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>
答案 0 :(得分: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?');
})