简体   繁体   中英

Why does my ajax call not returning my data from controller?

I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.

Here's my AJAX call

function GetRecord() {
    var elemEmployee = 55;
    var startDT = $('#searchFilterStartDate').val();
    var endDT = $('#searchFilterEndDate').val();

    $.ajax({
        url: "/Modules/GetDTRRecord",
        type: "GET",
        data: {
            EmployeeID: elemEmployee,
            DateFrom: endDT,
            DateTo: startDT,
        },
        dataType: "json",
        success: function(data) {


            console.log('Data Success ');

             console.log(data);


        }
    });
}

here's my controller:


        [HttpGet]
        public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
        {
            var entity = new DTRRecordList();
         
            return entity.GetDTR(data);
        }

As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console. 正如你在这里看到的,我有记录在此处输入图像描述

You need to return JSON from your Controller method. You can change your method to:

    [HttpGet]
    public JsonResult GetDTRRecord(DTRRecordList.Entity data)
    {
        var entity = new DTRRecordList();
        var getDTR= entity.GetDTR(data);
        return Json(new {dtrData= getDTR});
    }

And in your Ajax call:

$.ajax({
    url: "/Modules/GetDTRRecord",
    type: "GET",
    data: {
        EmployeeID: elemEmployee,
        DateFrom: endDT,
        DateTo: startDT,
    },
    dataType: "json",
    success: function(data) {
         console.log('Data Success ');
         console.log(data.dtrData);
    },
    error: function(error) {
        console.log(error)
    }
});

After a discussion with OP and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:

$(document).ready(function () {
    //On Clink "Search Button"
    $("#searchbtn").click(
    function () { GetRecord(); });
});

The data seems to be coming as expected.

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