开发者

Invoke an AsyncController Action from within another Controller Action?

开发者 https://www.devze.com 2022-12-26 23:42 出处:网络
I\'d like to accomplish the following: class SearchController : AsyncController { public ActionResult Index(string query)

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);
0

精彩评论

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

关注公众号