2

Here's the thing, I'm trying to update a view where an image and a DateTime are displayed. I want the image and the time to update without reloading the page. So after some research I found that using an Ajax call should do it.

For some reason neither the time or the image update after the ajax call and I can't figure out why.

Am I missing something, or it's not the way I should do it?

Please keep in mind, I am new to asp.net and Ajax. Thanks :)

Here's my View with the Ajax script:

@model myApp.Models.ImageViewModel
@{
    ViewBag.Title = "Image";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>    
    function refreshImage() {
        $.ajax({
            //url: "/Controller/ActionName",
            async: true,
            url: '/Image/GetImage',
            type: 'GET',
            success: function () {
                setTimeout(refreshImage, 5000);
            }
        });
    }

    $(document).ready(function () {
        setTimeout(refreshImage, 5000);
    });
</script>

<div>
    <div class="panel panel-info">
        <div class="panel-heading"><h4>Image</h4></div>
        <div class="panel-body">
            <div class="ImgContainer">
                <img src=@Model.ImageUrl>
                <div>@Model.LastUpdateDate</div>
            </div>
        </div>
    </div>
</div>

And here's the controller method:

public ActionResult GetImage()
{
    DateTime lastUpdate = System.DateTime.Now;
    string imageUrl = "http://lorempixel.com/1920/1080/animals";
    ImageViewModel image = new ImageViewModel(lastUpdate, ImageUrl);

    Debug.WriteLine("test");

    return View(image);
}
Leojet
  • 61
  • 1
  • 8
  • add this to your ajax code: dataType:'image/jpg' and remove the async section. ( definitely don't need that ) – Neo Nov 09 '16 at 17:09

2 Answers2

0

Change your ajax call to this

function refreshImage() {
    $.ajax({
        dataType:'image/jpg',
        url: '/Image/GetImage',
        type: 'GET',
        success: function () {
            setTimeout(refreshImage, 5000);
        }
    });
}
Neo
  • 3,309
  • 7
  • 35
  • 44
  • Thanks for the suggestion, but unfortunately this did not solve my issue :( The image and the time were not updated. – Leojet Nov 10 '16 at 13:42
0

Ok so I figured out what was going on. Since the url I used wasn't changing I forced the refresh of the image with a dull parameter on the url and also got the time to update at the same time.

Now my ajax call look like this.

$.ajax({
   //url: "/Controller/ActionName"
   url: '/Image/GetImage',
   type: 'GET',
   success: function () {
       var time = new Date().toLocaleString();
       $("#imageCam").attr("src", "@Model.ImageUrl" + "?" + time);
       document.getElementById("theTime").innerHTML = time;

       setTimeout(refreshImage, 5000);
      }
   });

Hope this help someone in the future. See this question for more info How to reload/refresh an element(image) in jQuery

Community
  • 1
  • 1
Leojet
  • 61
  • 1
  • 8