Action Parameters in ASP.NET Tutorial 🎯

beginner
23 min

Action Parameters in ASP.NET Tutorial 🎯

Welcome to the Action Parameters lesson! In this tutorial, we'll explore how to handle user input and pass data to our ASP.NET MVC action methods.

Understanding Action Parameters 📝

Action parameters are a crucial part of ASP.NET MVC. They allow us to accept data from incoming requests and use it within our action methods.

Types of Action Parameters ✅

  1. Simple Parameters: These are used to receive scalar values such as integers, strings, or booleans.

  2. Complex Parameters: These are used to accept complex types, like custom objects or models.

  3. Route Parameters: These are special parameters used to define URL routes for routing purposes.

Simple Parameters 💡

Let's create a simple example to demonstrate the use of simple parameters.

csharp
public ActionResult DisplayMessage(string message) { return Content(message); }

In the above example, message is a simple parameter that accepts a string value from the incoming request.

Binding Simple Parameters 📝

By default, ASP.NET MVC can automatically bind simple parameters to their corresponding values from the incoming request. However, you can also explicitly bind simple parameters using the ModelBind attribute.

Complex Parameters 💡

Complex parameters allow us to pass complex types like custom objects or models to our action methods.

csharp
public class Person { public string Name { get; set; } public int Age { get; set; } } public ActionResult DisplayPerson(Person person) { return Content($"Name: {person.Name}, Age: {person.Age}"); }

In this example, Person is a complex parameter that accepts a Person object.

Route Parameters 💡

Route parameters are used to define URL routes for routing purposes.

csharp
public class HomeController : Controller { public ActionResult ShowDetails(int id) { // Your code here } } // Routing configuration routes.MapRoute( name: "Details", url: "details/{id}", defaults: new { controller = "Home", action = "ShowDetails", id = UrlParameter.Optional } );

In this example, id is a route parameter used in the URL to pass data to the ShowDetails action method.

Quiz 💡

Quick Quiz
Question 1 of 1

What are the three types of action parameters in ASP.NET MVC?