开发者

Asynchronous auto-refresh using asp.net MVC 3

I've written a simple progra开发者_如何学Cm that gathers some information from the WMI database such as the current CPU usage. I perform these operations in the homecontroller file, with an ActionResult Index function. Then I return the View and display these results on the homepage.

Now, I should use JQuery and refresh these values every 3 seconds. I don't want to reload the whole page. But, just these values that I gather from WMI.

Any good and simple(because I'm a complete newbie in Javascript) suggestions?


Alright, you asked for a suggestion, so I'll try and remain high-level.

First, you'll want to implement two views:

  1. Index - This is your view that's returned by your Index ActionResult functon on your controller.
  2. Stats - This is a partial view included in your Index view as such:

    <div id="refreshme">
        @Html.Partial("_Stats", Model.Stats)
    </div>
    

You'll note that I passed in a Model that contains a stats object. This stats object gets passed to your "Stats" View which will know how to render it.

Next, you'll want to add a new action method in your HomeController called, you guessed it, Stats! This ActionResult will just render the Stats view and return it as HTML. You'll also want to set a flag of [HttpGet] on it so it can accept get requests:

[HttpGet]
public ActionResult Stats(...)
{
    //...
    return View("_Stats", Model);
}

Now, for the JS side:

function refresh() {
    $.get('/index/post', function(result) {
        $('#refreshme').html(result);
    });
}
setInterval(refresh, 3000);

So the objectives are as such:

  1. Strip out your part that you want refreshed from the rest of the page and put it in a partial view.
  2. Add a controller action method that renders just that partial view.
  3. Include that partial view on your Index view with a container wrapped around it so it can be easily updated.
  4. Add a javascript function that'll get the latest view rendering from the controller and overwrite the current stats on the page.

Hopefully this will get you going in the right direction.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜