Ajax请求不向控制器发布ID

时间:2015-07-06 11:16:52

标签: javascript c# ajax asp.net-mvc-5

我已经向我的deletewidget控制器写了一个AJAX post请求,它正在发布请求令牌,但它似乎没有将widgetID传递给控制器​​。我已经逐步完成了javascript代码并将ID分配给变量widgetID,并且还在我的控制器中添加了一个断点,但它表示为null。

$(document).ready(function () {
    $('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
        var panel = this;
        //get id here

        //toggle the modal
        $('#deleteWidgetModal').modal('show');
        var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');

        document.getElementById('delete-widget').onclick = function (event) {
            event.stopPropagation();

            //anti forgery token
            //get the form
            var form = $('#__AjaxAntiForgeryForm');
            //from the form get the antiforgerytoken
            var token = $('input[name="__RequestVerificationToken"]', form).val();

            var URL = '/Dashboard/DeleteWidgetConfirmed';

            //we make an ajax call to the controller on click
            //because the controller has a AntiForgeryToken attribute
            //we need to get the token from the form and pass it with the ajax call.
            $.ajax({
                url: URL,
                data: {
                    __RequestVerificationToken: token,
                    id: widgetID   
                },
                type: 'POST',
                success: function(result){
                    var parentElement = $(panel).closest(".col-md-4.column");
                    var targetElement = $(panel).closest(".panel.panel-default");
                    targetElement.remove();

                    //parentElement.addClass("expand-panel");
                    checkEmptyPanelContainers();
                    $('#deleteWidgetModal').modal('hide');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("An error has occurred please contact admin");
                }
            })
        }
        return false;
    })
});

这是我的控制器

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteWidgetConfirmed(int? id)
    {
        if(id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        WidgetModel widgetModel = db.widgets.Find(id);
        db.widgets.Remove(widgetModel);
        db.SaveChanges();
        return new EmptyResult();
    }

1 个答案:

答案 0 :(得分:0)

它似乎是两次执行ajax代码,我将我的返回假移动了一级并解决了问题