You need to enable JavaScript to run this app. 如何为Blazor的InputNumber组件添加placeholder占位符
优惠活动
大模型
产品
解决方案
定价
更多

如何为Blazor的InputNumber组件添加placeholder占位符

Blazor InputNumber组件placeholder不生效解决方案

失效原因

  1. .NET 5及更早版本的原生InputNumber组件默认不自动透传未定义的自定义属性(如placeholder),需要手动通过AdditionalAttributes参数传递。
  2. .NET 6+版本已支持属性自动透传,此时失效多是因为绑定的Hour属性默认值为0而非null:InputNumber仅在绑定值为null时才会显示占位符,值为0时会渲染数字0,自然看不到占位符。

解决方案

方案1:通过AdditionalAttributes手动传参(全版本兼容)

直接在组件上用AdditionalAttributes传递placeholder属性即可:

<EditForm Model="FilteredEmployees">
  <InputNumber @bind-Value="Hour" 
               min="0" 
               max="10" 
               class="form-control"
               AdditionalAttributes="@(new Dictionary<string, object> { { "placeholder", "Hour" } })" />
</EditForm>

方案2:确保绑定属性默认值为null

你后台代码已经将Hour定义为可空类型int?,只需要删除初始化时给Hour赋值为0的逻辑即可,可空值类型的默认值就是null,满足占位符显示条件。

方案3:封装自定义InputNumber组件(适合批量使用场景)

如果多处需要用到带placeholder的InputNumber,可以自己封装扩展组件:

// CustomInputNumber.cs
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;

public class CustomInputNumber<TValue> : InputNumber<TValue>
{
    [Parameter]
    public string Placeholder { get; set; }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        if (!string.IsNullOrWhiteSpace(Placeholder))
        {
            AdditionalAttributes ??= new Dictionary<string, object>();
            AdditionalAttributes["placeholder"] = Placeholder;
        }
    }
}

封装完成后可以直接在razor页面使用:

<CustomInputNumber @bind-Value="Hour" 
                   min="0" 
                   max="10" 
                   class="form-control" 
                   Placeholder="Hour" />

内容的提问来源于stack exchange,提问作者Nb777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 14:57:02