Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"UpdatePanel" in Razor (mvc 3)

Is there something like UpdatePanel (in ASPX) for Razor?

I want to refresh data (e.g. table, chart, ...) automaticly every 30 seconds. Similar to clicking the following link every 30 seconds:

 @Ajax.ActionLink("Refresh", "RefreshItems", new AjaxOptions() {
     UpdateTargetId = "ItemList",
     HttpMethod = "Post"})

Edit:

I may should add that the action link renders a partial view.

Code in cshtml:

<div id="ItemList">
  @Html.Partial("_ItemList", Model)
</div>

Code in Controller:

    [HttpPost]
    public ActionResult RefreshItems() {
        try {
            // Fill List/Model
            ... 

            // Return Partial
            return PartialView("_ItemList", model);
        }
        catch (Exception ex) {

            return RedirectToAction("Index");
        }
    }

It would be create if the PartielView could refresh itself.

like image 720
Tobias Avatar asked May 03 '11 07:05

Tobias


2 Answers

You can try something similar to the following using Jquery (have not tested though)

<script type="text/javascript">
   $(document).ready(function() {
        setInterval(function()
        {
         // not sure what the controller name is
          $.post('<%= Url.Action("Refresh", "RefreshItems") %>', function(data) {
           // Update the ItemList html element
           $('#ItemList').html(data);
          });
        }
        , 30000);
   });
</script>

The above code should be placed in the containing page i.e. not the partial view page. Bear in mind that the a partial view is not a complete html page.

My initial guess is that this script can be placed in the partial and modified as follows. Make sure that the ajax data type is set to html.

<script type="text/javascript">
    setInterval(function()
    {
      // not sure what the controller name is
      $.post('<%= Url.Action("Refresh", "RefreshItems") %>', function(data) {
        // Update the ItemList html element
        $('#ItemList').html(data);
      });
    }
    , 30000);
</script>

Another alternative is to store the javascript in a separate js file and use the Jquery getScript function in ajax success callback.

like image 79
Ahmad Avatar answered Oct 04 '22 23:10

Ahmad


Well, if you don't need the AJAX expierience than use the HTML tag:

<meta http-equiv=”refresh” content=”30; URL=http://www.programmingfacts.com”>

go here: http://www.programmingfacts.com/auto-refresh-page-after-few-seconds-using-javascript/

like image 39
Julian S Avatar answered Oct 04 '22 21:10

Julian S