Blazor Data Binding

Blazor is a component-based framework that supports powerful capabilities such as data binding. Data binding is simply a bridge or connection between your application View and Data. When the data changes, the View automatically reflects the updated data values. With data binding, direct access to the DOM is minimized. In terms of development, you just need to point or connect a HTML element with a variable defined in your program. For example, you can write the following:

@page "/"
<h3>Data Binding</h3>

<p>@dataBinding</p>

@functions {
    string dataBinding = "Test Data Binding";
}

When you run the above, your web page will display "Test Data Binding". To make the example more interesting, we are going to bind to the same variable with the input HTML element using the bind keyword. After running the program, you can change the input value, press the Enter key and see that the value in @dataBinding changes automatically.

@page "/"
<h3>Data Binding</h3>

Enter value: <input type="text" @bind=dataBinding /><br />
<p>@dataBinding</p>

@functions {
    string dataBinding = "Test Data Binding";
}

To make the example more meaningful, you can use bind to display a list of values.

@page "/"
<h3>Data Binding

<ul>
    @foreach (var day in days)
    {
      <li>@day</li>
    }
</ul>

@functions {
	private List<string> days { get; set; } = new List<string>
        {
	        "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
        };
}

The following example shows how to display the days in a drop down list using the HTML select element. When the selection changes, the SelectDay function will be executed to update the selectedDay value.

@page "/"
    
<select @onchange=SelectDay>
    @foreach (var day in days)
    {
      <option value=@day>@day</option>
    }
</select>

<p>Today is :@selectedDay</p>

@functions {
    private List<string>
    days { get; set; } = new List<string>
    {
    	"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
    };
    string selectedDay = "Monday";
    void SelectDay(ChangeEventArgs e)
    {
    	selectedDay = e.Value.ToString();
    	Console.WriteLine("Today is: " + selectedDay);
    }
}

Format Bindings

If you wish to format a bound value, you can use the format-value attribute. The Birthday for input element uses the format-value="dd.MM.yyyy".

@page "/"
<h3>Data Binding</h3>

<input type="text" @bind="Birthday" format-value="dd.MM.yyyy" />
<p>
    You are born on the @Birthday
</p>
@functions {
	public DateTime Birthday { get; set; } = DateTime.Today;
}