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:
- Index - This is your view that's returned by your Index ActionResult functon on your controller.
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:
- Strip out your part that you want refreshed from the rest of the page and put it in a partial view.
- Add a controller action method that renders just that partial view.
- Include that partial view on your Index view with a container wrapped around it so it can be easily updated.
- 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.
精彩评论