gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:46:42 25 4
gpt4 key购买 nike

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

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

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

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

管理 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>

最佳答案

使用[HttpPost]属性标记您的方法

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

并更改 View 以使用表单而不是 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?');
})

关于asp.net - Action 方法不适用于asp.net MVC中的[HttpPost]属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34690155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com