Search code examples
c#javascriptasp.net-mvcdynamic-data

Need advice for dynamic update table value (C#, MVC3, JavaScript)


I have html page with table on it. Simplify it may look at:

<Row_ID>, <bla-bla-bla>, <_XXX.XX%_ is complete> 

In C# I has a function that evaluate "% is complete" by ID. But it operation may take some times (not instant and may cause some delay )

Now I need implement auto-refresh of "% is complete" that will be update data in one or two minutes interval. I do not want to reload neither entire page nor entire table (if I do it by ajax). Because user may look at the page and the reloading will brake its current position (or even rows counts in the table).

So I think about javascript setTimeout that call some function and to get values from server (by JSON?) But I'm not sure about web-page freeze when javascript function will request data. May be there are another update methods exists?

Any versions or suggestions are welcome!

Sorry for my broken English.


Solution

  • This should accomplish what you mean. I am assuming you will make a single call to return a JSON result of multiple results (most efficient). Also, jQuery ajax calls are asynchronous, so there will be no page 'freeze' - also, just guessing at your MVC Model setup, but I think you get the idea?

    <table>
        @foreach(var line in Model)
        {
        <tr>
            <td>@line.Id</td>
            <td>@line.Something</td>
            <td id="p-@line.Id">@line.Percentage% complete</td>                   
        </tr>
        }
    </table>
    

    JS:

    var to;
    $().ready(function() {
        ResetUpdate();
    });
    
    function Update() {
        // do your $.ajax();
        // if success,
        // assuming return data is an array like:
        var data = [ {id:1, p:26}, {id:2, p:99} ];
        for(var i = 0; i < data.length; i++) {
            $('#p-' + data[i].id).html(data[i].p + '% complete');            
        }
        ResetUpdate();
    }
    
    function ResetUpdate() {
        to = setTimeout("Update()", 120000); //2 minutes
    }
    

    Here is the jsFiddle.