Site icon WP Reset

How to Get a Variable from HTML Input in Blazor C#

Code

Blazor is a powerful framework for building interactive web applications with C# rather than JavaScript. One of the core features of Blazor is the ability to bind C# code with HTML elements, making it easy to capture user inputs and use them in your application. In this article, we’ll explore how to get a variable from an HTML input element in Blazor, both in Blazor Server and Blazor WebAssembly applications.

Introduction to Blazor’s Two-Way Data Binding

Blazor offers a feature known as “two-way data binding,” which allows changes in the user interface (UI) to automatically update the underlying C# variable, and vice versa. This is extremely useful when you want to capture data entered by the user into an HTML input field and immediately reflect those changes in your C# code.

Getting Started

To get a variable from an HTML input field, you need a few key components:

  1. HTML Input: The input field where the user enters data.
  2. C# Variable: The C# variable that stores the data from the input.
  3. Data Binding: The connection between the input field and the C# variable, typically through the @bind directive in Blazor.

In the following sections, we’ll walk through various examples to demonstrate how this works.

Example 1: Simple Text Input Binding

The simplest way to capture a user’s input is by using the @bind directive. This automatically binds an HTML input element to a C# variable.

Code Example (Razor Component)

@page "/input-example"

<h3>Simple Input Binding in Blazor</h3>

<label for="userName">Enter your name:</label>
<input type="text" id="userName" @bind="userName" />

<p>Hello, @userName!</p>

@code {
    private string userName = string.Empty;
}

Explanation:

  1. The @bind directive binds the input element to the userName variable in C#. Whenever the user types into the input field, the userName variable is automatically updated.
  2. The paragraph <p>Hello, @userName!</p> dynamically displays the value of userName, showing the updated text in real-time as the user types.

In this example, the variable userName is tied to the input field, and Blazor’s two-way binding ensures that whenever the user modifies the text, the value of userName is updated in real-time.

Example 2: Getting and Using Input on Button Click

Sometimes you need to perform actions on the data entered by the user, such as clicking a button to submit the value or process it further. This can also be easily achieved in Blazor.

Code Example (Razor Component)

@page "/submit-input"

<h3>Submit Input in Blazor</h3>

<label for="age">Enter your age:</label>
<input type="number" id="age" @bind="age" />

<button @onclick="SubmitAge">Submit</button>

<p>You entered: @age</p>

@code {
    private int age;

    private void SubmitAge()
    {
        // Do something with the age variable (e.g., validation, submission, etc.)
        Console.WriteLine($"User's age is {age}");
    }
}

Explanation:

  1. The @bind="age" directive binds the input field to the age variable.
  2. The @onclick="SubmitAge" binds the button’s click event to the SubmitAge method.
  3. When the user clicks the button, the SubmitAge method is called, which prints the entered age to the console.

In this example, the user can enter their age, and when they click the “Submit” button, the SubmitAge method is triggered to perform an action with the age variable.

Example 3: Input Validation

Blazor allows you to perform input validation easily by combining data binding with form components like <EditForm>.

Code Example (Razor Component)

@page "/validation-example"

<h3>Input Validation in Blazor</h3>

<EditForm Model="@person" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <label for="firstName">First Name:</label>
    <InputText id="firstName" @bind-Value="person.FirstName" />
    <ValidationMessage For="@(() => person.FirstName)" />

    <button type="submit">Submit</button>
</EditForm>

<p>You entered: @person.FirstName</p>

@code {
    private Person person = new Person();

    private void HandleValidSubmit()
    {
        // Process the valid input
        Console.WriteLine($"First Name: {person.FirstName}");
    }

    public class Person
    {
        [Required]
        public string FirstName { get; set; }
    }
}

Explanation:

  1. The <EditForm> component is used to wrap the input fields and perform validation.
  2. The @bind-Value="person.FirstName" binds the input field to the FirstName property of the person object.
  3. The DataAnnotationsValidator component uses data annotations (such as [Required]) to validate the input.
  4. If the input is valid and the form is submitted, the HandleValidSubmit method is called, processing the data.

Validation:

Advanced Binding with Other Input Types

Blazor supports a wide range of input types, such as text boxes, checkboxes, radio buttons, dropdowns, etc. You can bind variables to any of these elements in a similar way.

Example: Checkbox Binding

@page "/checkbox-example"

<h3>Checkbox Binding in Blazor</h3>

<label for="subscribe">Subscribe to newsletter:</label>
<input type="checkbox" id="subscribe" @bind="isSubscribed" />

<p>You are @(isSubscribed ? "subscribed" : "not subscribed") to the newsletter.</p>

@code {
    private bool isSubscribed = false;
}

In this example, the checkbox is bound to the isSubscribed variable, and when the user checks or unchecks the box, the value of isSubscribed is automatically updated.

Conclusion

Getting a variable from an HTML input in Blazor is easy and efficient, thanks to Blazor’s powerful two-way data binding. By using the @bind directive, you can quickly link input fields to C# variables, ensuring that changes in the UI are reflected in your code and vice versa.

Whether you’re building simple forms or complex input validation logic, Blazor’s data binding capabilities simplify the process of working with user inputs. From text boxes to checkboxes, Blazor handles the integration between HTML and C# seamlessly, making it an excellent choice for building interactive web applications.

Exit mobile version