Skip to content

Custom input component not behaving as expected #58869

Open
@tmonte

Description

@tmonte

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Defining a custom "TextInput" component per docs:

@using Microsoft.AspNetCore.Components.Forms
@inherits InputBase<string>

<input type="text" @bind="CurrentValue" />

@code
{
  protected override bool TryParseValueFromString(string? value, out string result, out string?
  validationErrorMessage)
  {
    result = value ?? "";
    validationErrorMessage = null;
    return true;
  }
}

Using it inside an EditForm

@page "/my-form"
@inject ILogger<MyForm> Logger

<EditForm Model="Model" OnSubmit="Submit" FormName="MyForm">
    <div>
        <label>
            Base:
            <InputText @bind-Value="Model!.Value1" />
        </label>
    </div>
    <div>
        <label>
            Custom:
            <TextInput @bind-Value="Model!.Value2" />
        </label>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</EditForm>

@code {
    [SupplyParameterFromForm]
    private Example? Model { get; set; }

    protected override void OnInitialized() => Model ??= new();

    private void Submit() 
    {
        Logger.LogInformation("Value1 = {Value1}", Model?.Value1);
        Logger.LogInformation("Value2 = {Value2}", Model?.Value2);
    }

    public class Example
    {
        public string? Value1 { get; set; }
        public string? Value2 { get; set; }
    }
}

Result in logs is:

info: Example.Pages.MyForm[0]
      Value1 = test
info: Example.Pages.MyForm[0]
      Value2 = (null)

Am I missing anything in the Custom Input definition? I've also tried inheriting InputText directly, but had the same results. I couldn't find anything else in the docs.

Expected Behavior

Result in logs should be:

info: Example.Pages.MyForm[0]
      Value1 = value1
info: Example.Pages.MyForm[0]
      Value2 = value2

Steps To Reproduce

  1. Clone repo https://github.com/tmonte/blazor-example and run it
  2. Go to /my-form
  3. Enter a value for the "Base" input, like: "value1"
  4. Enter a value in the "Custom" input, like: "value2"
  5. Observe results in log - Value for Custom input is null

Exceptions (if any)

No response

.NET Version

8.0.403

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocsThis issue tracks updating documentationarea-blazorIncludes: Blazor, Razor Components

    Type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions