2012-11-14 29 views
0

當我刪除使用jQuery.ajax與POST方法DB的項目,我得到這個錯誤:在CategoryControllerjQuery的阿賈克斯POST在MVC3

GET Http://localhost:54010/Admin/Category/Delete?id=77 404 Not Found 

操作:

[HttpPost] 
public ActionResult Delete(int id) { 
    try { 
    db.CategoryRepository.Delete(id); 
    db.Save(); 
    return Json(new {Result = "OK"}); 
    } catch (Exception ex) { 
    return Json(new { Result = "ERROR", Message = ex.Message }); 
    } 
} 

查看:

<a id="delete-category" class="btn btn-small" href="#"> 
    <i class="icon-remove"></i> 
    @Resource.delete 
</a> 

的JavaScript:

$(function() { 
    $('#delete-category').click(function (event) { 
    event.preventDefault(); 
    $.ajax({ 
     method: 'POST', 
     url: '@Url.Action("Delete","Category")', 
     dataType: 'json', 
     data: { id: '@Model.CategoryModel.Id' }, 
     success: function (data, textStatus, jqXHR) { 
     console.log("success"); 
     }, 
     error: function() { 
     alert('error'); 
     } 
    }); 
    }); 
}); 

爲什麼click事件不生成POST?

回答

5

你需要告訴ajax()方法,通過設置type參數做出post要求:

$.ajax({ 
    // method: 'POST', <-- remove this 
    type: 'POST', // <-- add this 
    url: '@Url.Action("Delete","Category")', 
    dataType: 'json', 
    data: { id: '@Model.CategoryModel.Id' }, 
    success: function (data, textStatus, jqXHR) { 
     console.log("success"); 
    }, 
    error: function() { 
     alert('error'); 
    } 
});