Invoke an AsyncController Action from within another Controller Action?
I'd like to accomplish the following:
class SearchController : AsyncController
{
public ActionResult Index(string query)
{
if(!isCached(query))
{
// here I want to asynchronously invoke the Search action
}
else
{
ViewData["results"] = Cache.Get("results");
}
return View();
}
publ开发者_运维技巧ic void SearchAsync()
{
// some work
Cache.Add("results", result);
}
}
I'm planning to make an AJAX 'ping' from the client in order to know when the results are available, and then display them.
But I don't know how to invoke the asynchronous Action in an asynchronous way!
Thank you very much. Luis
You could invoke the action in a new thread:
if(!isCached(query))
{
new Thread(SearchAsync).Start();
}
The view could use an AJAX call to an action that would check if the results are available:
public ActionResult Done(string query)
{
return Json(new
{
isDone = !isCached(query),
result = Cache.Get(query)
});
}
And the ping:
var intId = setInterval(function() {
$.getJSON('/search/done', { query: 'some query' }, function(json) {
if (json.isDone) {
clearInterval(intId);
// TODO : exploit json.result
} else {
// TODO: tell the user to wait :-)
}
});
}, 2000);
精彩评论