Add read-only fields to Blazor EditForm

120 Views Asked by At

I have a Blazor server app on which I am doing input validation in an EditForm as follows

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

    <InputText @bind-Value="model.Name" />
    <InputText @bind-Value="model.FirstName"/>
    <!-- Here I'd like to show a disabled input (for design) with one-way binding 
    <InputText Value="@(model.DisplayName)" ValueExpression="@(() => model.DisplayName)" disabled="true" />
    <button type="submit">Submit</button>
</EditForm> 

// ---- model class
public class Person {
    [Required]
    public string Name { get; set; }
    [Required]
    public string FirstName { get; set; }
    // --- 
    public string DisplayName => $"{FirstName} {Name}".Trim();
}

Note I cannot use two-way binding since DisplayName has no setter.

The above works, but I have to manually add the ValueExpression despite not requiring validation for that particular property. Is there a way to flag a particular editor (readonly or not) as not necessary for validation - so I don't have to worry about adding its ValueExpression?

1

There are 1 best solutions below

1
On

Since the field is read-only, you don't have to use an InputText control. You can use a div with the appropriate styles to make it look like an InputText control.

    <div class="form-control bg-light">@model.DisplayName</div>