删除操作不激活/触发ASP.NET MVC的核心

问题描述 投票:0回答:2

HttpPost上删除操作不会触发,但似乎HTTPGET工作正常,因为我得到显示的内容。但是我有,当我上HTTPGET点击删除操作生成以下路由地址有点慌乱: -

https://localhost:44394/9

它不应该产生链接这样的:https://localhost:44394/Post/DeletePost/9

控制器: -

[HttpPost, ActionName("DeletePost")]
public async Task<IActionResult> ConfirmDelete(int id)
{          
     await _repository.DeletePostAsync(id);             
     return RedirectToAction(nameof(GetAllPosts));           
 }
[HttpGet("{id}")]
public async Task<IActionResult> DeletePost(int id)
{
  var post = await _repository.GetPostById(id);
  if(post == null)
   {
     return NotFound();
   }
    return View(post);
}

Razor视图的HTTPGET: -

 <div class="btn btn-outline-danger delete">
    <a href="@Url.Action("DeletePost", "Post", new { id = p.Id })">Delete
    </a>
</div>

剃刀页HttpPost: -

<div class="container">
    <div class="row">
        <div class="col-9">
            <p>
                @Model.Topic
            </p>
            <p class="timeStampValue" data-value="@Model.Published">
                @Model.Published
            </p>
            <p>
                @Model.Author
            </p>
            <section>
                <markdown markdown="@Model.Content" />
            </section>
        </div>
    </div>

    <form asp-action="DeletePostAsync"> 
        <input type="hidden" asp-for="Id" />
        <button type="submit" class="btn btn-outline-danger">Delete</button>
    </form>
    <a href="@Url.Action("GetAllPosts", "Post")" class="btn btn-outline-secondary">Cancel</a>
</div>

路由:-

app.UseMvc(routes =>
{     routes.MapRoute(
      name: "KtsPost",
      template: "{controller}/{action}/{id?}",
      defaults: new { controller = "Post", action = "Index" },
     constraints: new { id = "[0-9]+" });
      });
asp.net-mvc asp.net-web-api razor
2个回答
1
投票

你的动作名称是错误的形式。你的代码应该改为:

<form asp-action="DeletePost"> 
    <input type="hidden" asp-for="Id" />
    <button type="submit" class="btn btn-outline-danger">Delete</button>
</form>

0
投票

HTML表单的默认方法是GETPOST。你需要告诉你的形式POST。此外,行动名称应该是ConfirmDelete

<form asp-action="ConfirmDelete" method="post"> 
    <input type="hidden" asp-for="Id" />
    <button type="submit" class="btn btn-outline-danger">Delete</button>
</form>
© www.soinside.com 2019 - 2024. All rights reserved.