0

How can I get data from the controller with ajax.

Method in my Controller

 public ActionResult StartPage()
    {
        var result = CommonService.GetCurrentDateTime();
        ViewBag.DateAndTimeFromDataBase = result ;
        return View();
    }

and my Ajax

$(document).ready(function() {
    setInterval('getServerDateTime()', 0, 1000);
});

function getServerDateTime() { 
    $.ajax({
        type: 'GET',
        cache: false,
        url: "/Login/StartPage",
        complete: function (req, textStatus) {
            var dateString = req.getResponseHeader('Date'); 
            if (dateString.indexOf('GMT') === -1) {
                dateString += ' GMT';
            }
            var date = new Date(dateString);
            $('#time-span').text(dateString);
        }
    });
};

Here I get the date time from the server. And I wanted to take the value of the time date from the controller. And display the difference therebetween. I am new to this. I can’t get the result of that in the controller.

<div>
    <span id="time-span" class="date-time"></span>
</div>
S.A.R
  • 47
  • 6
  • If you want to get data back from your controller, you have to return something more than just View(). You will have to inject your model into the return i.e. View(model). Check this out: https://stackoverflow.com/questions/5980389/proper-way-to-use-ajax-post-in-jquery-to-pass-model-from-strongly-typed-mvc3-vie – LinkedListT Apr 27 '20 at 20:03
  • https://stackoverflow.com/questions/26670994/c-sharp-return-json-instead-of-a-view-mvc/26671120 – Mertuarez Apr 27 '20 at 20:35

1 Answers1

1

Considering that this is an AJAX request you are likely better off returning the data as a JSON payload. You can do that by modifying your code like so:

public JsonResult StartPage()
{
    var date = CommonService.GetCurrentDateTime();
    return Json(new { date });
}

this will return a payload to the client that looks something like this:

{
    "date": "<the value of GetCurrentDateTime() as a String>"
}

This can then be easily accessed via your JavaScript code like so:

$.ajax({
    type: 'GET',
    cache: false,
    url: "/Login/StartPage",
    complete: function (response) {
        var dateString = response.date;
        if ( !dateString ) {
            console.error('A001: date not returned from server');
        }

        if (dateString.indexOf('GMT') === -1) {
            dateString += ' GMT';
        }
        var date = new Date(dateString);
        $('#time-span').text(dateString);
    }
});

You should note that .NET has a funky way of serializing timestamps that may not work for JS, you may want to format the date serverside to something more understandable for JavaScript (see then options for DateTime.ToString())

Menachem Hornbacher
  • 2,080
  • 2
  • 24
  • 36