DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Mapping asp.net request data to controller action simple parameter types

In ASP.NET, you can map incoming request data to controller action parameters in several ways, depending on the parameter type. Here are some common parameter types and how you can map them:

  1. Simple Types (e.g., int, string): For simple types, ASP.NET automatically maps query string or form data values with matching parameter names. For example, if your action method has a parameter named "id" of type int, ASP.NET will automatically map the value of "id" from the query string or form data to that parameter.

Example:

   public IActionResult MyAction(int id)
   {
       // Use the 'id' parameter value
       return View();
   }
Enter fullscreen mode Exit fullscreen mode
  1. Model Binding: ASP.NET provides model binding to automatically map complex types from request data. Model binding can be used for parameters of custom types or complex objects. It maps request data based on parameter names and property names in the object.

Example:

   public IActionResult MyAction(MyModel model)
   {
       // Use properties of the 'model' object
       return View();
   }
Enter fullscreen mode Exit fullscreen mode
  1. FromQuery Attribute: You can use the [FromQuery] attribute to explicitly indicate that a parameter should be bound from the query string, even for simple types.

Example:

   public IActionResult MyAction([FromQuery] string name)
   {
       // Use the 'name' parameter value from the query string
       return View();
   }
Enter fullscreen mode Exit fullscreen mode
  1. FromForm Attribute: The [FromForm] attribute allows you to explicitly indicate that a parameter should be bound from form data, even for simple types.

Example:

   public IActionResult MyAction([FromForm] int age)
   {
       // Use the 'age' parameter value from the form data
       return View();
   }
Enter fullscreen mode Exit fullscreen mode

These are some common ways to map request data to controller action parameters in ASP.NET. You can choose the appropriate method based on the parameter type and the source of the data (query string, form data, etc.).

Top comments (0)