Search code examples
c#blazorasp.net-blazor

How to bind a value to a class property?


I am new to web development and new to C#/Blazor.

I am therefore working on a pet project of mine. In this project, I have a page where I would like the user to input some numbers.

I would like to, dynamically, bind those values to a class and then use that class to perform calculations and display those results dynamically so that as soon as the user changes the inputs, the results get updated without the need for clicking on a "submit" button or anything like that. The basic idea is therefore to have a live calculator of some sort.

I am using MudBlazor framework to speed things up. Here is my starting code located in Pages/Project.razor :

<MudItem xs="12" sm="6" md="4">
  <MudNumericField @bind-Value="Project.NumDays" Label="Number of days" Variant="Variant.Text" Min="0" Max="10000" />
</MudItem>

@code {
  public class Project
  {
    public string NumDays // property
    { get; set; }
  }
}

Right now, the app is stating that it can't recognize the Project class. How can I achieve what I want ? Is this possible ? Or do I need to define the Project class outside the Pages directory ?


Solution

  • You must instantiate the Project class... You can't use the class definition identifier as a value to the @bind-Value directive attribute. Do that like this:

    Project project = new Project();

    Your code should look like this:

    <MudItem xs="12" sm="6" md="4">
      <MudNumericField @bind-Value="project.NumDays" Label="Number of days" Variant="Variant.Text" Min="0" Max="10000" />
    </MudItem>
    
    
    @code {
        Project project = new Project();
    
      public class Project
      {
        public string NumDays { get; set; } // property
        
      }
    }
    

    Note that the Project instance starts with lowercase p