Live Chat Icon For mobile
Live Chat Icon

Blazor FAQ

Find answers for the most frequently asked questions
Expand All Collapse All

To upload files in Blazor applications, install the NuGet package, BlazorInputFile. This package has the component, InputFile  that isused to upload files.
You also need to include the input file scripts in HTML and add BlazorInputs to the _Imports.razor file.

[_Host.cshtml]

  <script src="_content/BlazorInputFile/inputfile.js"></script>
[index.razor]

@page "/upload"

<h3>Upload</h3>

<InputFile OnChange="HandleFileSelected"  class="btn-primary"/>

@if (file != null)
{
    <p>Name: @file.Name</p>
    <p>Size in bytes: @file.Size</p>
    <p>Last modified date: @file.LastModified.ToShortDateString()</p>
    <p>Content type (not always supplied by the browser): @file.Type</p>
}

@code {
    IFileListEntry file;

    void HandleFileSelected(IFileListEntry[] files)
    {
        file = files.FirstOrDefault();
    }
}

You can handle multiple file uploads by adding multiple attribute to the InputFile component.

@page "/multiupload"

<h3>Multiple File Upload</h3>

<InputFile multiple OnChange="HandleFileSelected"  class="btn-primary"/>

@if (file != null)
{
   <p>Name: @file.Name</p>
   <p>Size in bytes: @file.Size</p>
    <p>Last modified date: @file.LastModified.ToShortDateString()</p>
    <p>Content type (not always supplied by the browser): @file.Type</p>
}

@code {
    IFileListEntry file;

    void HandleFileSelected(IFileListEntry[] files)
    {
        file = files.FirstOrDefault();
    }
}

Please refer to this link here for more information on file uploading in Blazor.

Note: Syncfusion offers feature rich as well as easy to use file upload component. For more information, please check the link.

Permalink

You can check/uncheck the checkbox in the Blazor programmatically by using the @bind parameter in the checkbox. Assign a Boolean property to @bind in the checkbox and toggle the Boolean property programmatically.

@page 
<input type="checkbox" @bind="@boolvalue" />
<br />
Checkbox: @val
<br />
<button class="btn btn-primary" @onclick="@ToggleCheckbox ">toggle</button>

@code {

public bool boolvalue { get; set; }
public string val;
 void ToggleCheckbox()
 {
        if (boolvalue)
        {
            val = "unchecked";
        }
        else
        {
            val = "checked";
        }
        boolvalue = !boolvalue;
}
}

Permalink

To set the active value on a select dropdown control, you must bind a property to the value in the select component and change that bind property in the event call

@page "/dropdown"


<select class="form-control" value="@listdefault" @onchange="@OnSelect" style="width:150px">
    @foreach (var template in templates)
    {
<option value=@template>@template</option>
     }
</select>

<h5>@selectedString</h5>
<select class="form-control" value="@citydefault" @onchange="@OnSelectCity" style="width:150px">
       @foreach (var template in citytemplates)
        {
   <option value=@template>@template</option>
}
</select>
<h5>@selectedCity</h5>
<button class="btn btn-primary" @onclick="@Change">Change</button>

@code {
    List<string> templates = new List<string>() { "America", "China", "India", "Russia", "England" };
    List<string> citytemplates = new List<string>();
    List<string> usa = new List<string>() { "Los-Angeles", "Florida", "Newyork", "Washington", "California" };
    List<string> china = new List<string>() { "Wuhan", "Beijing", "Shanghai", "Macau", "Taipei " };
    List<string> india = new List<string>() { "New-Delhi", "Mumbai", "Chennai", "Bangalore", "Hyderabad" };
    List<string> russia = new List<string>() { "Moscow", "Saint Petersburg", "Novosibirsk", "Yekaterinburg", "Kazan" };
    List<string> england = new List<string>() { "Birmingham", "Cambridge", "Manchester", "Leicester", "London" };
    string selectedString = "";
    string selectedCity = "";
    string listdefault = "India";
    string citydefault = "Mumbai";
    void OnSelect(ChangeEventArgs e)
    {
        if (e.Value.ToString() == "America")
        {
            citytemplates = usa;
        }
        else if (e.Value.ToString() == "China")
        {
            citytemplates = china;
        }
        else if (e.Value.ToString() == "India")
        {
            citytemplates = india;
        }
        else if (e.Value.ToString() == "Russia")
        {
            citytemplates = russia;
        }
        else
        {
            citytemplates = england;
        }
        selectedString = "Selected Country is: " + e.Value.ToString();

        StateHasChanged();
        Console.WriteLine("It is definitely: " + selectedString);
    }
    void OnSelectCity(ChangeEventArgs e)
    {
        selectedCity = "Selected CIty is: " + e.Value.ToString();
        Console.WriteLine("It is definitely: " + selectedString);
    }
    void Change(MouseEventArgs args)
    {
        listdefault = "Russia";
    }
    protected override void OnInitialized()
    {
        citytemplates = india;
        citydefault = "Chennai";
        base.OnInitialized();
    }
}

In the above sample, the city dropdown is changed based on the country selected in the country dropdown.

Permalink

The property value in the select control can be used to set the default value in select control.

@page "/dropdown"

<select class="form-control" value="@defaultValue " @onchange="@OnSelect" style="width:150px">
       @foreach (var template in templates)
        {
     <option value=@template>@template</option>
         }
 </select>

<h5>@selectedString</h5>

@code {
List<string> templates = new List<string>() { "America", "China", "India", "Russia", "England" };
string selectedString = "";
string defaultValue = "India";
void OnSelect(ChangeEventArgs e)
{
       selectedString = "Selected Country is: " + e.Value.ToString();
}
    }
Permalink

To retrieve a selected value from the select control, you can use either the @bind or @onchange event.

//using @bind

@page "/dropdown"
<select class="form-control" @bind="@selectedString" style="width:150px">
         @foreach (var template in templates)
         {
                 <option value=@template>@template</option>
         }
</select>

<h5>Selected Country is: @selectedString</h5>

@code {
List<string> templates = new List<string>() { "America", "China", "India", "Russia", "England" };
string selectedString = "America";
    }
//using @onchange event

@page "/dropdown"

<select class="form-control"  @onchange="@OnSelect" style="width:150px">
         @foreach (var template in templates)
         {
                 <option value=@template>@template</option>
         }
</select>

<h5>Selected Country is: @selectedString</h5>

@code {
List<string> templates = new List<string>() { "America", "China", "India", "Russia", "England" };
string selectedString = "America";

void OnSelect (ChangeEventArgs e)
{
        selectedString = e.Value.ToString();
        Console.WriteLine("The selected country is : " + selectedString);
}
    }

Permalink

We can focus an InputText Blazor element not directly but by using JavaScript in Blazor. We can set an ID for the InputText and then pass it to JavaScript using interop by method InvokeVoidAsync. In the JavaScript function, use the focus DOM input method for focusing the input element with the received ID from Blazor.

Refer to the following code snippet.

[script.js]
function focusInput(id) {
    document.getElementById(id).focus();
}

Refer the script file in the HTML page

[index.html/_Host.cshtml]
<head>
 .....
 <script src="~/script.js"></script>
 ....
</head>
[Index.razor]

@page "/"

@inject IJSRuntime jsRuntime

<EditForm Model="@inputText">
    <InputText id="@InputID" @bind-Value="inputText.TextValue">You can enter some text...</InputText>
</EditForm>

<br />
<br />

<button @onclick="Focus">FOCUS!!!</button>

@code {

    public string InputID = "input-id";
    public string Output = "";

    public class InputTextClass
    {
        public string TextValue = "Some Random Text";
    }

    public InputTextClass inputText = new InputTextClass();

    public async Task Focus()
    {
        await jsRuntime.InvokeVoidAsync("focusInput", InputID);
    }
}
Permalink

To carry out form validation in a Blazor server-side application, use data annotations to enable validation for the forms. Also, include <DataAnnotationsValidator  /> and <ValidationSummary /> in the forms.

Refer to the following code sample.

@page "/employeedetails"
@using System.ComponentModel.DataAnnotations;

<EditForm Model="@_employee" OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
 <ValidationSummary />
    <InputText id="name" @bind-Value="_employee.Name" />
    <button type="submit">Submit</button>
</EditForm>

@code {
    public class Employee
    {
        [Required]
        [StringLength(10, ErrorMessage = "Name is too long.")]
        public string Name { get; set; }
    }

    private Employee _employee = new Employee();

    private void HandleValidSubmit()
    {
         Console.WriteLine("OnValidSubmit");
    }
}
Permalink

Two-way binding is having a bidirectional data flow, i.e., passing the value from the property to the UI and then from the view (UI) to the property. Blazor provides support for two-way binding using the bind attribute.

Syntax for creating two-way binding property:

@bind-{Parameter_name}={Variable_name}

For e.g.., in InputDate, a form component can be used to achieve two-way data binding with input date values in a Blazor application.

Refer to the following code for more details.

<EditForm Model="@_test">
    <InputDate @bind-Value="_test.DateValue" />
</EditForm>

<br />

<p>Selected Date: @_test.DateValue.ToLongDateString()</p>

@code {
    
    public class TestClass
    {
        public DateTime DateValue { get; set; }
    }

    private TestClass _test = new TestClass();
}

In this example code, when the value of _test.DateValue is changed in the code or user changes the date in the InputDate component, the same will be reflected in the paragraph, “Selected Date”.

Permalink

One-way (unidirectional) binding is all about moving data in one direction from the “Parameter/Property” to the UI (components). You just need to add the @ symbol to the variable name (for example, @yourVariable).

For example, one-way binding with an input date value can be achieved using the InputDate component (form component in Blazor) as follows in an application.

<EditForm Model="@_test">
    <Input type="Date" Value="@_test.DateValue" />
</EditForm>

@code {
    
    public class TestClass
    {
        public DateTime DateValue { get; set; }
    }

    private TestClass _test = new TestClass();
}

In this example, the property DateValue in _test class is bound to the InputDate component’s value property using the value attribute. A form is defined by the EditForm component.

Permalink

Blazor provides support for validating form input using data annotations with the built-in DataAnnotationsValidator.

The ValidationSummary can be used to display error messages for all the fields. It can also be used to display custom error messages.

The <DataAnnotationsValidator/> and <ValidationSummary /> components only validate top-level properties. It does not validate the collection or complex-type properties of the model class. The Model class needs to be bound to the EditForm component.

Blazor provides ObjectGraphDataAnnotationsValidator to validate the entire model object including collection and complex-type properties. This component is defined in Microsoft.AspNetCore.Blazor.DataAnnotations.Validation package and currently it is in an experimental stage.

@page "/employeedetails"
@using System.ComponentModel.DataAnnotations;

<EditForm Model="@_employee" OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
 <ValidationSummary />
    <InputText id="name" @bind-Value="_employee.Name" />
    <button type="submit">Submit</button>
</EditForm>

@code {
    public class Employee
    {
        [Required]
        [StringLength(10, ErrorMessage = "Name is too long.")]
        public string Name { get; set; }
    }

    private Employee _employee = new Employee();

    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}
Permalink

You can use the following CSS classes to apply your own styles to validation messages.

CSS class name Added DOM element 
valid/invalid Added to the <input> element of DOM 
validation-errors  Added to the dynamically created <ul>
element while using the
<ValidationSummary> tag 
validation-message Added to the dynamically created <div> / <li>
element which holds to error message. 

<div> – created while using
<ValidationMessage> tag 
<li> – created while using
<ValidationSummary> tag 
modified Added to the <input> element after modifying the default value. 
Permalink

You have to use the <ValidationMessage> tag with the “For” attribute lambda expression pointing to the form field.

[Person.cs]

using System.ComponentModel.DataAnnotations;
public class Person
    {
        [Required]
        [StringLength(15, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
        public string FirstName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [StringLength(15, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
        public string LastName { get; set; }

        [Required]
        [Range(1, 100, ErrorMessage = "Age should a number between (1-100).")]
        public int Age { get; set; }
    }

[FormValidation.Razor]

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

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

  <label for="lastname">Last Name: </label>
  <InputText Id="lastname" @bind-Value="@person.LastName"></InputText>
  <ValidationMessage For="@(() => person.LastName)" />

  <label for="age">Age: </label>
  <InputNumber Id="age" @bind-Value="@person.Age"></InputNumber>
  <ValidationMessage For="@(() => person.Age)" />

  <button type="submit">Submit</button>
</EditForm>
@code {
    private Person person = new Person();
    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}
Permalink

The form validation in Blazor is achieved using data annotations. The following two tags are used for validations and display the validation error message:

  • <DataAnnotationsValidator />
  • <ValidationSummary />

Refer to the following code example for simple form validation in Blazor.

[Person.cs]

using System.ComponentModel.DataAnnotations;
public class Person
    {
        [Required]
        [StringLength(15, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
        public string FirstName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [StringLength(15, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
        public string LastName { get; set; }

        [Required]
        [Range(1, 100, ErrorMessage = "Age should a number between (1-100).")]
        public int Age { get; set; }
    }

[FormValidation.razor]

<EditForm Model="@person" OnValidSubmit="@HandleValidSubmit">
   <DataAnnotationsValidator />
   <ValidationSummary />
    <label for="firstname">First Name: </label>
    <InputText Id="firstname" @bind-Value="@person.FirstName"></InputText>

    <label for="lastname">Last Name: </label>
    <InputText Id="lastname" @bind-Value="@person.LastName"></InputText>

    <label for="age">Age: </label><br />
    <InputNumber Id="age" @bind-Value="@person.Age"></InputNumber>

    <button type="submit">Submit</button>
</EditForm>
@code {
    private Person person = new Person();
    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}
Permalink

You have to use the EditContext with EditForm to validate the forms inside a bootstrap modal.

@using System.ComponentModel.DataAnnotations;

<div id="modalDialog" class="modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <EditForm EditContext="@EC">
                    <DataAnnotationsValidator />
                    <ValidationSummary />

                    <div class="form-group d-flex justify-content-between">
                        <label class="col-form-label col-3" for="name">Name</label>
                        <InputText bind-Value="@model.Name" id="name" Class="form-control" />
                    </div>
                    @if (EC.Validate())
                    {
                        <button type="button" onclick="@SubmitHandler" class="btn btn-primary" data-dismiss="modal">Submit</button>
                    }
                    else
                    {
                        <button type="button" onclick="@SubmitHandler" class="btn btn-primary">Submit</button>
                    }
                </EditForm>
            </div>
        </div>
    </div>
</div>
<button data-toggle="modal" data-target="#modalDialog" class="btn btn-primary">Open</button>

@code {
    public class ModelClass
    {
        [Required]
        public string Name { get; set; }
    }
    private ModelClass model { get; set; } = new ModelClass();
    private EditContext EC { get; set; }
    private void SubmitHandler()
    {
        Console.WriteLine("Submit");
    }
    protected override void OnInitialized()
    {
        EC = new EditContext(model);
        base.OnInitialized();
    }
    }
Permalink

You have to define and bind the EditContext with EditForm and then call the method editContext.Validate() on button click to manually trigger the validation.

@using System.ComponentModel.DataAnnotations;

<EditForm EditContext="@EC">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div class="form-group d-flex justify-content-between">
        <label class="col-form-label col-3" for="name">Time</label>
        <InputText bind-Value="@model.Name" id="name" Class="form-control" />
    </div>
    <button type="button" onclick="@SubmitHandler" class="btn btn-primary">Submit</button>
</EditForm>
@code {
    public class ModelClass
    {
        [Required]
        public string Name { get; set; }
    }
    private ModelClass model { get; set; } = new ModelClass { Name = "" };
    private EditContext EC { get; set; }
    protected override void OnInitialized()
    {
        EC = new EditContext(model);
        base.OnInitialized();
    }
    private void SubmitHandler()
    {        
        EC.Validate(); // manually trigger the validation here
    }
}
Permalink

You can define the form attribute validation in a Razor component inside the function to achieve this. Please do not forget to include the DataAnnotations in the Razor component file.

@using System.ComponentModel.DataAnnotations;

<EditForm Model="@model" OnValidSubmit="@SubmitHandler">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <div class="form-group d-flex justify-content-between">
        <label class="col-form-label col-3" for="name">Name</label>
        <InputText @bind-Value="@model.Name" id="name" Class="form-control" />
    </div>
    
    <button type="submit" @onclick="@SubmitHandler" class="btn btn-primary">Submit</button>
</EditForm>
@code {
    public class ModelClass
    {
        [Required]
        public string Name { get; set; }
    }
    private ModelClass model = new ModelClass();
    private void SubmitHandler()
    {
        Console.WriteLine("Submit");
    }   
}

Please refer to this documentation for more form validations.

Permalink

You have to use the format-value string “yyyy-MM-ddTHH:mm” to work with AM/PM conversion properly.

<input type="datetime-local" id="Test" name="Test" class="form-control" @bind="@testDateTime" format-value="yyyy-MM-ddTHH:mm" />

@code {
    DateTime testDateTime { get; set; } = new DateTime(2019, 12, 15, 16, 45, 15);
}

Refer to this thread for more information.

Permalink

Yes, this is a known issue in Blazor. You can track the issue link in the ValueChanged event not fired thread.

The following code snippet will work. You have to update the model manually because handling the ValueChanged event does not let you use the @bind-Value we need to use ValueExpression instead of @bind-Value.

<EditForm Model="person">
    <DataAnnotationsValidator />
    <div class="form-group">
        <label for="name">Name</label>
        <InputText ValueChanged="@ValueChange" Value="@person.FirstName" ValueExpressions= "@( () => @person.FirstName )" Class="form-control" Id="name" />
    </div>
</EditForm>

@code { 
    Person person = new Person();
    public void ValueChange()
    {
        Console.WriteLine(person.FirstName);
    }
}

Instead, you can also use the OnValidSubmit form event to get and process the value.

<EditForm Model="person" OnValidSubmit="@ValueChange">
  <DataAnnotationsValidator />
   <div class="form-group">
     <label for="name">Name</label>
     <InputText @bind-Value="@person.FirstName" Class="form-control" Id="name" />
   </div>
</EditForm>

@code { 
    Person person = new Person();
    public void ValueChange()
    {
        Console.WriteLine(person.FirstName);
    }
}
Permalink

Share with

Share on twitter
Share on facebook
Share on linkedin

Couldn't find the FAQs you're looking for?

Please submit your question and answer.