简体   繁体   中英

How to call controller from jquery in MVC?

I want to call my controller from view by Jquery which returns count. While debugging the result variable returns as undefined. Please someone correct my code.

View:

<script type="text/javascript">
$(function () {
    $('.icon-delete').click(function () {
        debugger;
        var v = 'e8a6bdf4-1da6-41e0-8423-86ffacf71703';
       var result= GetCollectionCount(v);
        var answer = confirm('Do you want to delete this record?');
        if (answer) {
            $.post(this.href, function () {
                window.location.reload(); //Callback
            });
            return false;
        }
        return false;
    });
});

function GetCollectionCount(id) {
    $.ajax({
        type: 'POST',
        contentType: "application/json;charset=utf-8",
        url: '/AdminNew/CollectionCount',
        dataType: 'json',
        data: { "id": id },
        //traditional: true,
        success: function (ajaxresult) {
            //alert(ajaxresult);
            return ajaxresult;
        },
        failure: function (ajaxresult, status) {
            console.log(ajaxresult)
        }
    });
}

While debugging the result variable returns as undefined.

That's normal and is how AJAX works. The first A in AJAX stands for Asynchronous . This means that the $.ajax function doesn't return anything. It is used to trigger an AJAX request to the server and the only single place where you can use the results of this AJAX call is inside the success callback. In your example you seem to be attempting to use those results immediately.

The problem is GetCollectionCount is making an Asynchronous request to the server. That is to say the rest of your code continues to execute and does not wait for the request to finish.

You need to place the code dependant on the request in a callback that is executed upon a successful request:

$(function () {
    $('.icon-delete').click(function () {
        debugger;
        var v = 'e8a6bdf4-1da6-41e0-8423-86ffacf71703';
        GetCollectionCount(v);
    });
});

function GetCollectionCount(id) {
    $.ajax({
        type: 'POST',
        contentType: "application/json;charset=utf-8",
        url: '/AdminNew/CollectionCount',
        dataType: 'json',
        data: { "id": id },
        //traditional: true,
        success: function (ajaxresult) {
            var answer = confirm('Do you want to delete this record?');
            if (answer) {
              $.post(this.href, function () {
                window.location.reload(); //Callback
              });
              return false;
            }
            return false;
        },
        error: function (ajaxresult, status) {
            console.log(ajaxresult)
        }
    });
}

You should try something like that :

$(function () {
    $('.icon-delete').click(function () {
        debugger;
        var v = 'e8a6bdf4-1da6-41e0-8423-86ffacf71703';
        GetCollectionCount(v);
    });
});

function GetCollectionCount(id) {
    $.ajax({
        type: 'POST',
        contentType: "application/json;charset=utf-8",
        url: '/AdminNew/CollectionCount',
        dataType: 'json',
        data: { "id": id },
        //traditional: true,
        success: getCollectionSuccess,
        error: errorCallback
    });
}

function getCollectionSuccess(ajaxResult){
    var answer = confirm('Do you want to delete this record?');
        if (answer) {
            $.post(this.href, function () {
                window.location.reload(); //Callback
            });
            return false;
       }
}

function errorCallback(errorMsg, status){
    console.log("Error Message : "+errorMsg+" Error code : "+status);
}

Maybe setting async to false gets away the problem @Darin mentioned:

function GetCollectionCount(id) {
$.ajax({
    // ... your settings

    async: false,

    success: function (ajaxresult) {
        //alert(ajaxresult);
        return ajaxresult;
    },
    failure: function (ajaxresult, status) {
        console.log(ajaxresult)
    }
});

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM