首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >AJAX删除操作到错误的方法

AJAX删除操作到错误的方法
EN

Stack Overflow用户
提问于 2014-02-19 23:05:33
回答 1查看 1.6K关注 0票数 0

我试图通过一个AJAX调用从数据库中删除一条记录,如下所示:

代码语言:javascript
运行
复制
$.ajax({
    type: 'POST',
    url: '/api/Person/DeletePerson',
    data: { personId: personId },
    contentType: 'application/json',
    success: function (data) {
        if (data != null) {

        }
    },
    error: function (err, data) {
        alert("Error " + err.responseText);
    }
});

这是它应该输入的方法:

代码语言:javascript
运行
复制
public void DeletePerson(int personId)
{
var t = 0; // i'm breaking the debugger right here, never gets hit.
}

但是,它却不断地输入以下方法:

代码语言:javascript
运行
复制
public HttpResponseMessage PostPerson(dynamic person)
{
    HttpResponseMessage response;

    if (User.Identity.GetUserId() == null)
    {
        response = Request.CreateResponse(HttpStatusCode.Forbidden, "Please log in."); 
    }

    return response;
}

这两个方法都驻留在一个WebApi Controller中。

不支持AJAX Type: delete。如果我用它来代替,我就会得到这样的信息:

代码语言:javascript
运行
复制
The requested resource does not support http method 'delete'

我该怎么做呢?

编辑

代码语言:javascript
运行
复制
public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-19 23:09:59

要调用Delete方法(因为这是rest实现),可以使用DELETE谓词调用/api/Person/ URL。

代码语言:javascript
运行
复制
$.ajax({
    type: 'DELETE',
    url: '/api/Person',
    data: { personId: personId },
    contentType: 'application/json',
    success: function (data) {
        if (data != null) {

        }
    },
    error: function (err, data) {
        alert("Error " + err.responseText);
    }
});

否则,您需要更新操作以接受delete谓词

代码语言:javascript
运行
复制
[HttpDelete]
public void DeletePerson(int personId)
{
var t = 0; // i'm breaking the debugger right here, never gets hit.
}

如果希望使控制器从JSON有效负载而不是请求URL中查找id,请按以下方式重写。

代码语言:javascript
运行
复制
public void DeletePerson([FromBody]int personId)
{
    var t = 0; // i'm breaking the debugger right here, never gets hit.
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21894523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档