Search code examples
c#asp.net-mvcasynchronousactionresult

Asp.NET return ActionResult while adding data to user session


I have a method similar to this one:

 public ActionResult Index() 
 {    
    Session["test"] = GetData();
    return View(); 
 }

Because my GetData() method takes too long, I was wondering if i can do something async in order to return the View while GetData() is running and adding the object to user session. I already thought at splitting this method into 2 methods the first to return 'View()' and the second one to be called with ajax and just for adding object to session, but i want to use this as a last resort.

Thanks in advance!


Solution

  • Because my GetData() method takes too long, I was wondering if i can do something async in order to return the View while GetData() is running and adding the object to user session.

    You definitely do not want to run long running query on initial page load. User might think the network connection was lost, and keeps pressing F5 to refresh the page.

    Instead, you want two action methods -

    1. 1st Action Method returns regular view. Then at client-side, you make Ajax request to Action Method 2.

    2. 2nd Action Method returns JSON response

    FYI: You want to make sure 2nd Action Method requires user login to access. Otherwise, you might encounter DDoS attack.