What is Model Binding in ASP.NET Core? See Example

Model Binding in ASP.NET Core automatically maps incoming HTTP request data (from forms, query strings, route data, or JSON) to C# parameters or models. It simplifies handling user input and reduces manual parsing.

Key Features:

  • Automatically maps request data to action parameters
  • Supports complex models and collections
  • Works with MVC, Razor Pages, and Web API
  • Reduces boilerplate code for data handling
  • Supports custom model binders for advanced scenarios

Example:
Controller action with model binding:

public class AccountController : Controller
{
    [HttpPost]
    public IActionResult Login(UserModel user)
    {
        return Content($"Username: {user.Username}, Password: {user.Password}");
    }
}

public class UserModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

In a Razor view, posting a form:

<form asp-action="Login" method="post">
    <input asp-for="Username" />
    <input asp-for="Password" type="password" />
    <button type="submit">Login</button>
</form>

Model Binding in ASP.NET Core streamlines input processing and makes applications more maintainable and readable.

Citations:

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *