aspdotnet_model_binding.md - brainchildservices/curriculum GitHub Wiki

Slide 1

Model Binding

Model Binding in Razor Pages is the process that takes values from HTTP requests and maps them to handler method parameters or PageModel properties. Model binding reduces the need for the developer to manually extract values from the request and then assign them, one by one, to variables or properties for later processing

  • Binding Posted Form Values to PageModel Properties

    • This approach involves adding public properties to the PageModel (or to a @functions block if you don't want to use the PageModel approach) and then decorating them with the BindProperty attribute.
  • Then the code behind wiil be

     public class CalculatorModel : PageModel
     {
    
        [BindProperty]
        public string Length { get; set; }
        [BindProperty]
        public string Width { get; set; }
    
        public void OnGet()
        {
        }
    
        public void OnPost()
        {
        }
    
     }
    

Slide 2

  • From version 2.1 of ASP.NET Core, you can add the new [BindProperties] attribute to the PageModel class rather than applying [BindProperty] to individual properties, which results in all the public properties in the PageModel taking part in model binding:

      [BindProperties]
      public class CalculatorModel : PageModel
      {
         public string Length { get; set; }
         public string Width { get; set; }
    
         public void OnGet()
         {
         }
        
         public void OnPost()
         {
         }
       }
    

Slide 3

Binding Complex Objects

  • Fortunately model binding also works with complex objects. So the properties to be bound can be wrapped in an object that can be exposed as a property of the PageModel or a parameter for the handler method.

Here's a class named Login that represents the form fields

  public class Calculator
  {
     public string Length { get; set; }
     public string Width { get; set; }
  }

Slide 4

  • Now this can be added as a property on the PageModel class:

     public class CalculatorModel : PageModel
     {
         [BindProperty]
         public Calculator Calculator { get; set; }
    
         public void OnGet()
         {
         }
    
         public void OnPost()
         {
           ViewData["welcome"] = $"Welcome {Calculator.Length}";
         }
     }
    

Slide 5

  • Or it can be applied as a parameter to the OnPost method depending on your usage needs:

    public class CalculatorModel : PageModel
    {
        public void OnGet()
        {
        }
    
        public void OnPost(Calculator Calculator)
        {
           ViewData["welcome"] = $"Welcome {Calculator.Length}";
        }
    }
    
  • The form field names have to be altered to reflect the fact that the property has changed:

    <input type="text" class="form-control" name="Calculator.Length">