如何在ASP.NET中发送PUT和DELETE表单?

我已经为这个问题苦苦挣扎了一段时间,阅读一堆诸如此类的文章:

Razor Pages AJAX FORM

MSDN ASP.NET Core RESTfull Web API

并且没有掌握正确的方法。

在我当前的项目中,我有:

  1. 我认为的表单:
<form method="delete" asp-route="ProductCatalogSingle">
    <input hidden type="number" name="Id" value="@Model.Id" />
    <input type="submit" class="btn btn-dark" value="Delete" />
</form>
  1. 哪些人必须向我的操作发送删除请求:
// Controller have [Route("product-catalog")] attribute 

[HttpDelete("product",Name = "ProductCatalogSingle")]
public async Task<IactionResult> DeleteSingleItem(int id)
{
    // business-logic part responsible for data managment
    await logic.RemoveDataModelAsync(new ProductCatalog { Id = id });
    return RedirectToRoute("ProductCatalogAll");
}

// other action with same route,but different method
[HttpGet("product",Name = "ProductCatalogSingle")]
public async Task<IactionResult> SingleItem(int id)
{...}

在默认设置下,它不起作用-而是加载“获取操作”。

所以我尝试了很多事情:

  1. 使用同时具有"/product-catalog/product""@Url.Link("ProductCatalogSingle",null)"而不是url的Fetch API:
@section scripts{
    <script>
        document.forms[0].onsubmit = () => {
            let formData = new FormData(document.forms[0]);
            fetch(url,{
                method: "DELETE",body: new URLSearchParams(formData)
            })
                .then(() => {
                    alert('Deleted using Fetch');
                });
            return true;
        };
    </script>

我收到警报通知,但请求未发送。

  1. 使用非结构化AJAX:
@section scripts{
    <script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.js"></script>
}

<form method="delete" asp-route="ProductCatalogSingle" data-ajax="true" data-ajax-method="delete">
    <input hidden type="number" name="productId" value="@item.ProductId" />
     <input type="submit" class="btn btn-dark" value="Delete" />
</form>
  1. 纯JQuery AJAX
@section scripts{
<script>
    $(function () {
        $('#submit').on('click',function (evt) {
            evt.preventDefault();
            $.ajax({
                type: "DELETE",url: '/product-catalog/product?id=4001'
            });
        });
    });
</script>
  1. 更改IIS Express服务器变量,例如IIS Express FAQ状态
<add name="ExtensionlessUrl-Integrated-4.0" ... verb="GET,HEAD,POST,DEBUG,PUT,DELETE"

这些都不起作用。

sonya501 回答:如何在ASP.NET中发送PUT和DELETE表单?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3153949.html

大家都在问