简体   繁体   中英

Get Int value from Controller to $.Ajax

I want to pass int value from controller and check if it is greater than 0 in $.ajax. I don't know how to do it. I have tried a code but it is giving me undefined value. Going data in controller is working fine. But returning int value not able to do.:

AJAX Code:

function bindForm(dialog,urlString) {
    $('form', dialog).submit(function () {
    var data_send = $(this).serializeArray();
    $.ajax({
        url: urlString, 
        type: this.method,
        data: $(this).serialize(),
        success: function (result) {
        alert(result.success);
        if (parseInt(result.success, 10) > 0) {
            alert('Details Added Successfully');
            $('#dialog-form').dialog('close');
            var hdnInvoiceId = document.getElementById("Invoice_Id");
            hdnInvoiceId.value = parseInt(result.success, 10);
            $('#addInvoiceDetail').hide();
            } else {
            alert('Please Re-enter Details');
            bindForm();
            }
        }
    });
    return false;
});

Controller Code:

[HttpPost]
public int AddInvoice(Invoice model)
{
    int Invoice_Id = CRMServiceDL.insertInvoiceDetail(model);
    int success;
    if (Invoice_Id > 0)
    {
        success = Invoice_Id;
    }
        else {
        success = -1;

    }
    return success;
}

You need to return Json

[HttpPost]
public JsonResult AddInvoice(Invoice model)
{
    int invoiceId = CRMServiceDL.insertInvoiceDetail(model);
    int success = invoiceId > 0 ? invoiceId : -1;

    return Json(new { success });
}

Just use result in your success callback rather then result.success.

Result itself will contain the value you returned.

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