ASP.NET MVC > Asynchronous

Create asynchronous controller and action methods in ASP.NET MVC

How to create an asynchronous controller and action methods in ASP.NET MVC?


To create asynchronous controller, follow almost same steps as we have followed while creating a controller for a Model.

Clicking Add button, opens up another dialog box. Select appropriate Model class.

Select “User async controller actions” checkbox (it is important as this is what creates the Asynchronous controller, otherwise it creates normal controller.). Now give the Controller name as we wish. No need to suffix with “Async” word. We have done it just to differentiate with other controller of the same Model in this project.

A sample asynchronous action method

 public async Task<ActionResult> Index()
        {
            return View(await db.PersonalDetails.ToListAsync());
        }

Now, if we try to differentiate between the normal controller and asynchronous controller action methods, following things differs

  1. Return type is prefixed with async keyword that notifies that this action method returns data asynchronously.
  2. The return type is Task<ActionResult> that represent an asynchronous operation that can return a value.
  3. Also notice that any database operation using Entity Framework is prefixed with await keyword that waits for the data to be retrieved from the database asynchronously.
  4. Also note that instead of using ToList() method we are using ToListAsync() method that returns the data asynchronously.
Remaining everything is same as normal controller action methods.
The views are also similar to the normal controller scaffolding templates.
 Views: 16533 | Post Order: 114



Write for us






Hosting Recommendations