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:
- 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();
}
- 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();
}
- 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();
}
- 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();
}
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)