Asp.Net Core Action Methods Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET Core Action Methods

Introduction to ASP.NET Core Action Methods

In ASP.NET Core MVC, an Action Method is a public method in a controller class that handles client requests and returns HTTP responses. These methods form the core of the ASP.NET MVC application, orchestrating the process of data retrieval, business logic execution, and view rendering.

Key Characteristics

  1. Public Access Modifier: Action methods must be public so that they can be invoked by the framework.
  2. No Parameters, One Parameter, or Multiple Parameters: They can accept parameters from the URL, query string, or form data.
  3. Return Types: Action methods return an ActionResult which can be any of the following:
    • ViewResult for rendering a view.
    • PartialViewResult for rendering a partial view.
    • JsonResult for returning JSON data.
    • FileResult for returning files.
    • RedirectResult for redirecting to another URL.
    • StatusCodeResult for returning HTTP status codes.
    • ContentResult for returning text content.
    • EmptyResult for returning no content.

Example of Action Methods

Here's a simple example of an action method:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult About(string id)
    {
        ViewData["Message"] = "About Us";
        return View(id);
    }

    [HttpPost]
    public IActionResult Contact(ContactViewModel model)
    {
        if (ModelState.IsValid)
        {
            // Process the model
            return RedirectToAction("ThankYou");
        }
        return View(model);
    }

    public IActionResult ThankYou()
    {
        return View();
    }
}

Different Types of Action Methods

  1. Parameter-less Action Methods:

    public IActionResult Index()
    {
        return View();
    }
    
  2. Action Methods with Parameters:

    public IActionResult Details(int id)
    {
        var product = _productService.GetProductById(id);
        return View(product);
    }
    
  3. Action Methods with Complex Types:

    [HttpPost]
    public IActionResult Edit(ProductViewModel model)
    {
        if (ModelState.IsValid)
        {
            _productService.UpdateProduct(model);
            return RedirectToAction("Index");
        }
        return View(model);
    }
    
  4. Action Methods with Multiple Parameters:

    public IActionResult Search(string keyword, int? categoryId)
    {
        var products = _productService.SearchProducts(keyword, categoryId);
        return View(products);
    }
    

Attributes in Action Methods

Attributes in ASP.NET Core MVC are used to define metadata and behavior for controllers and action methods. Some important attributes are:

  • [HttpGet] and [HttpPost]: Specify the HTTP method that an action method should respond to.
  • [Route]: Define custom routes for action methods.
  • [Authorize] and [AllowAnonymous]: Control access to action methods.
  • [ValidateAntiForgeryToken]: Protect against cross-site request forgery (CSRF).
  • [ValidateAntiForgeryToken]: Prevent cross-site request forgery (CSRF) attacks.

Returning Different Types of Results

  • ViewResult: Returns a complete HTML page.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET Core Action Methods

ASP.NET Core Action Methods: Complete Examples, Step by Step for Beginners

Step 1: Set Up Your ASP.NET Core Web Application

  1. Install Visual Studio Community Edition:

    • Download and install Visual Studio Community Edition if you haven't already. It is free and includes all the necessary tools to develop ASP.NET Core applications.
  2. Create a New Project:

    • Launch Visual Studio.
    • Create a new project by selecting "File" > "New" > "Project".
    • Choose the "ASP.NET Core Web App (Model-View-Controller)" template.
    • Name your project (e.g., MyFirstAspNetCoreApp) and choose a location to save it.
    • Click "Create".

Step 2: Understand Basic Action Methods

Action methods are public methods inside a controller that handle incoming HTTP requests and produce an HTTP response.

Step 3: Create a New Controller

  1. Add a Controller:

    • In the Solution Explorer, right-click on the "Controllers" folder.
    • Select "Add" > "Controller".
    • Choose "MVC Controller - Empty".
    • Name the controller (e.g., HelloController).
    • Click "Add".
  2. Define a Simple Action Method:

    • Open the HelloController.cs file.
    • Add an Action Method named Index that returns a View:
    using Microsoft.AspNetCore.Mvc;
    
    namespace MyFirstAspNetCoreApp.Controllers
    {
        public class HelloController : Controller
        {
            public IActionResult Index()
            {
                return View();
            }
        }
    }
    

Step 4: Create a View for the Action Method

  1. Add a View:

    • In Solution Explorer, right-click on the Views folder.
    • Create a folder named Hello (this must match the controller name).
    • Right-click on the Hello folder and select "Add" > "Razor View".
    • Name the view Index.
    • Click "Add".
  2. Define the View Content:

    • Open the Index.cshtml file.
    • Write a simple greeting message:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Hello View</title>
    </head>
    <body>
        <h1>Hello, World!</h1>
    </body>
    </html>
    

Step 5: Test the Application

  1. Run the Application:

    • Press F5 or click the "Start" button in Visual Studio.
    • The browser should open and navigate to https://localhost:<port>/.
  2. Access the Action Method:

    • Manually navigate to https://localhost:<port>/Hello/Index.
    • You should see the "Hello, World!" message displayed.

Step 6: Explore Other Action Method Return Types

Action methods can return different types of results, such as ViewResult, JsonResult, FileResult, ContentResult, and more.

  1. Return a View with Data:

    • Modify the Index method to pass a message to the view:
    public IActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET Core!";
        return View();
    }
    
    • Update the Index.cshtml to display the message:
    <h1>@ViewBag.Message</h1>
    
  2. Return a JSON Result:

    • Add a new action method GetData:
    public IActionResult GetData()
    {
        var data = new { Name = "John", Age = 30 };
        return Json(data);
    }
    
    • Navigate to https://localhost:<port>/Hello/GetData to see the JSON response.
  3. Return a Content Result:

    • Add a new action method GetContent:
    public IActionResult GetContent()
    {
        return Content("This is a plain text content.");
    }
    
    • Navigate to https://localhost:<port>/Hello/GetContent to see the plain text.

Step 7: Handle Different HTTP Methods

Action methods can be attributed with [HttpGet], [HttpPost], [HttpPut], [HttpDelete], and more to handle different HTTP methods.

  1. Handle HTTP GET:

    • Add a method with the [HttpGet] attribute:
    [HttpGet]
    public IActionResult GetDetails()
    {
        ViewBag.Message = "Details for GET request.";
        return View();
    }
    
    • Create a GetDetails.cshtml view and add a message.
    • Navigate to https://localhost:<port>/Hello/GetDetails to test the GET method.
  2. Handle HTTP POST:

    • Create a new view PostData.cshtml for the form:
    @model MyFirstAspNetCoreApp.Models.UserModel
    
    <form method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" />
        <br />
        <label for="email">Email:</label>
        <input type="text" id="email" name="email" />
        <br />
        <input type="submit" value="Submit" />
    </form>
    
    • Create a model class UserModel.cs:
    namespace MyFirstAspNetCoreApp.Models
    {
        public class UserModel
        {
            public string Name { get; set; }
            public string Email { get; set; }
        }
    }
    
    • Add an action method to display the form [HttpGet] and another to handle the form submission [HttpPost]:
    public IActionResult PostData()
    {
        return View();
    }
    
    [HttpPost]
    public IActionResult PostData(UserModel model)
    {
        ViewBag.Message = $"Received: Name = {model.Name}, Email = {model.Email}";
        return View();
    }
    
    • Navigate to https://localhost:<port>/Hello/PostData to test the POST method.

Step 8: Custom Route Configuration

You can customize the routes in the Startup.cs file or directly in the controller using the [Route] attribute.

  1. Custom Route in Startup.cs:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
    
        app.UseRouting();
    
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "custom",
                pattern: "{controller=Hello}/{action=Index}/{id?}");
    
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    
  2. Using [Route] Attribute:

    [Route("[controller]/[action]")]
    public class HelloController : Controller
    {
        public IActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET Core!";
            return View();
        }
    
        [HttpGet]
        public IActionResult GetDetails()
        {
            ViewBag.Message = "Details for GET request.";
            return View();
        }
    
        [HttpGet]
        [Route("mydata")]
        public IActionResult GetData()
        {
            var data = new { Name = "John", Age = 30 };
            return Json(data);
        }
    }
    

Conclusion

You have now created an ASP.NET Core application with controllers and action methods handling different HTTP requests and responses. You've seen how to use different types of action method results and customize routes to make your application more flexible and powerful. Practice creating more controllers and actions with different HTTP methods and view models to deepen your understanding of ASP.NET Core.

Top 10 Interview Questions & Answers on ASP.NET Core Action Methods

1. What are ASP.NET Core Action Methods?

Answer: Action methods in ASP.NET Core are a form of public methods within the controller class that handle requests from the client, such as web browsers. They are called based on routing rules configured in the application. Action methods can return various types of responses, including views, JSON data, HTTP status codes, or even no response at all.

2. How do you return a View from an Action Method in ASP.NET Core?

Answer: To return a view from an action method, you can use the View() method. This method will render a view and send it back to the client. You can also pass data to the view by providing an object or a ViewData/ViewBag.

public IActionResult Index()
{
    var model = new YourModel { /* set properties */ };
    return View(model); // Renders Index.cshtml and passes 'model' to it
}

3. Can Action Methods Return JSON Data?

Answer: Yes, action methods can return JSON data. The Json() method is used to send JSON-formatted data to the client.

public IActionResult GetJson()
{
    var data = new { Property1 = "Value1", Property2 = "Value2" };
    return Json(data);
}

4. What is the difference between ViewResult and ActionResult in ASP.NET Core?

Answer: - ViewResult is a specific implementation of ActionResult that represents a view rendering result. It is used when you want to explicitly return a view from an action method. - ActionResult is a more general type that can be used to return any type of HTTP result, including views, redirections, JSON, files, etc. It makes the method signature more flexible.

public ActionResult Index() // Could return a View, Redirect, Json, File, etc.
public ViewResult Index() // Can only return a View

5. How can you perform data binding in Action Methods?

Answer: Data binding in ASP.NET Core can be achieved through model binding. ASP.NET Core automatically binds data in HTTP requests to parameters in action methods using a model binder.

public IActionResult Edit(int id, [FromBody] YourModel model)
{
    // 'id' is bound from the URL, 'model' is bound from the request body (usually POST or PUT requests)
}

6. How do you handle exceptions in Action Methods?

Answer: Exception handling in action methods can be done using try-catch blocks or by using global exception filters provided by ASP.NET Core.

public IActionResult Edit(int id)
{
    try
    {
        // Code that might throw an exception
    }
    catch (Exception ex)
    {
        // Handle exception
        return StatusCode(500, "Error processing request.");
    }
}

7. Can Action Methods return a Paged List of Items?

Answer: Yes, action methods can return a paged list of items by calculating the current page and total number of pages and passing this context to the view or returning the data as JSON.

public IActionResult List(int page = 1, int pageSize = 10)
{
    var totalItems = _context.Items.Count();
    var items = _context.Items.Skip((page - 1) * pageSize).Take(pageSize).ToList();
    var viewModel = new PaginatedViewModel
    {
        Items = items,
        CurrentPage = page,
        TotalPages = (int)Math.Ceiling(totalItems / (double)pageSize)
    };
    return View(viewModel);
}

8. How do you perform Content Negotiation in Action Methods?

Answer: Content negotiation in ASP.NET Core can be done by setting the Accept header in the request. The server will attempt to return the response in the format requested by the client. Framework features like Json() and Xml() methods aid in this.

[Produces("application/json", "application/xml")]
public IActionResult Get()
{
    var data = new YourModel { /* set properties */ };
    return Ok(data); // The data is automatically formatted based on the Accept header
}

9. What is Attribute Routing in ASP.NET Core Action Methods?

Answer: Attribute routing in ASP.NET Core allows developers to define routes on the controller or action methods directly using attributes, providing greater flexibility and clarity.

[Route("api/[controller]")]
public class ItemsController : Controller
{
    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        // Method implementation
    }
}

10. How can you perform Validation in Action Methods?

Answer: ASP.NET Core provides a powerful validation system using data annotations or custom validation logic. Validation results are available in the ModelState property within the controller.

You May Like This Related .NET Topic

Login to post a comment.