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.
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.
Simple Parameters: These are used to receive scalar values such as integers, strings, or booleans.
Complex Parameters: These are used to accept complex types, like custom objects or models.
Route Parameters: These are special parameters used to define URL routes for routing purposes.
Let's create a simple example to demonstrate the use of simple parameters.
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.
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 allow us to pass complex types like custom objects or models to our action methods.
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 are used to define URL routes for routing purposes.
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.
What are the three types of action parameters in ASP.NET MVC?