Link to home
Start Free TrialLog in
Avatar of axnst2
axnst2Flag for United States of America

asked on

Auto refresh part of an MVC5 View

Hi Experts,

I keep looking online and I just can't seem to find exactly what I am looking for.  I would like to take an existing View and have only part of that view be refreshed every 2 minutes with records from a database, and using this data, I want to be able to dynamically build a hyperlink that would allow me to navigate to another page while passing it data I retrieved from the DB as part of the refresh.

Here's what I mean:  My project is to add to an existing dashboard the ability to Alert the user monitoring it when someone has been in a particular room (for safety) for more than 2 minutes.  Another system inserts a record into a DB table when the person was detected in the room for 2+ minutes.  I just need to refresh just a part of my MVC5 dashboard, and read that record from the DB.  Then using the data I got from the DB, dynamically build a link to another page (already exists) passing it the person (who has been in the room for 2+ minutes)'s ID number.  Reading from the DB in a Controller is not my question, I do it all the time.  I just need to know how to refresh just a part of the View every few minutes, and display a link to another View, passing it the person's ID, which I retrieved from the DB.

Like:

Room Temperature: 130
People in room for over two minutes:

     <Section to refresh from DB every two minutes>

          George Washington            -> Link to another Controller/Function passing it 'ol Geroge's UserID
          Abraham Lincoln

     </Section to refresh from DB every two minutes>







Any help would be great!
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

E-E sent me a "neglected" alert on this question (not sure why -- I'm a PHP programmer) so I'll try to give a bit of the theory, even if I can't build a demonstration case.

The interaction between the client (HTML, CSS, JavaScript) and the server is driven by requests and responses, using the HTTP protocol.  This is often what we refer to as "AJAX requests" when the client machinery, often without direct human interaction, makes the HTTP request.  The responses from the server can be used to reload part of the Document Object Model, thereby changing the visible representation of the DOM in the browser viewport.

One of the features of JavaScript is its ability to remain stateful across HTTP requests.  It's still the same programming and data, still running in the client browser, so it keeps all of its scope, even as it initiates requests and receives data from the server.  One of the happy artifacts of this design is the ability to use a timer.  JavaScript gives us the setTimeOut() function that uses two parameters.  The first is a callback function that gets control when the timer expires.   The second is a timer value, given in milliseconds, so a value of 1,000 == 1 second.  Let's call this the "time-to-refresh" (TTR).

Since you have a 2-minute window of safety, it seems to me that you might want to be fairly accurate about how long someone has been in the room.  For this reason, a TTR of one or two seconds might be right.  Every time the JavaScript timer goes off, make an AJAX request to your server with the DB table.  The server will read the DB table and furnish a response (probably a JSON string) identifying the rooms, occupants, elapsed times, and any other information you might need.  Using this response from the server, your JavaScript can manipulate the DOM, adding or removing display information as appropriate.

This is a very abbreviated illustration of the timer concept.  It uses a TTR of 1000 (one second) and updates a counter on the web page.
https://iconoun.com/demo/temp_wesman.php
<!DOCTYPE html>
<!-- http://www.experts-exchange.com/questions/28934604/Refresh-div-using-javascript-No-meta-refresh.html -->
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style type="text/css">
/* STYLE SHEET HERE */
</style>

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
    var num = 1;
    var kount = function(){
        $("#renew #count").html(num);
        num = num + 1;
        setTimeout(kount, 1000);
    };

    kount();
});

</script>

<title>HTML5 Page demo/temp_wesman.php</title>
</head>
<body>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<div id="fixed">Fixed</div>
<div id="renew">Ever-changing <span id="count"></span></div>

</body>
</html>

Open in new window

A number of similar examples can be found across the WWW.  For example, this article shows how to update a progress bar to show the status of a long-running task on the server.  Hopefully the design pattern will be useful to you.
Avatar of axnst2

ASKER

Thanks for the attention!  

Do I see correctly that this is missing two components:
         1. the call to the Controller to retrieve the data
         2. the building of the hyperlinks in the View based on the data that was retrieved from the DB in the Controller

Thank you for the help!
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of axnst2

ASKER

I'm sorry but those examples do not help me much with my MVC pages.  Could someone with MVC5 experience help us?
Avatar of axnst2

ASKER

Okay, so I got this far.  However, the JavaScript function getDateTimeFunc only seems to be firing once.

Controller Code:

public JsonResult GetDateTime()
        {
            //logic here for getting your count
            var victimCount = DateTime.Now.ToString();

        return Json(victimCount, JsonRequestBehavior.AllowGet);
        }

Open in new window


View code:

@Scripts.Render("~/bundles/jquery")

<script type='text/javascript'>
    var timeoutId;

    $(function () {
        window.setInterval(getDateTimeFunc, 1000);
    });

    function getDateTimeFunc()
    {
        $.getJSON
        (
            "/Home/GetDateTime",
            function (dataResponse)
            {
                $('#CurrentDateTime').html(dataResponse);
            }
        );      
    }
</script>

<br />
<br />
<label id="CurrentDateTime">Nope</label>

Open in new window

Avatar of axnst2

ASKER

Here's the solution:

<script type="text/javascript"
        src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

<script>

    $(document).ready(
            function() {
                setInterval(function() {
                   
                    $.getJSON
                    (
                        "/Home/GetDateTime?t=" + (new Date()).getTime(),
                        function (dataResponse) {

                            $('#show').text(dataResponse);
                        }
                    );                    
                }, 3000);
            });
</script>

<br />
<br />
<div id="show" align="center"></div>

Open in new window

Avatar of axnst2

ASKER

It was actually my own last post that solved the problem, but I appreciate the effort nonetheless