首页 > 解决方案 > 将输入字段绑定到模型时不显示 HTML 输入字段占位符

问题描述

我有一个输入字段,用户可以在其中输入价格。我希望有一个0.00.

占位符仅在我删除模型绑定时才有效:asp-for="Postage"

为什么会这样?以及如何显示占位符?

HTML 输入框:

@model Website.Models.Game

<div class="form-group">
   <label asp-for="Postage"></label>
   <div class="input-icon">
      <input type="number" class="form-control postageInput" placeholder="0.00" asp-for="Postage"/>
      <i>£</i>
   </div>
</div>

该模型:

public class Game {
  [Key]
  public int Id {get; set;}

  [Required(ErrorMessage = "Enter postage amount or click on 'collection only'")]
  public decimal Postage {get; set;}

  [other properties here below...]
}

标签: c#htmlasp.net-corerazor-pagesmodel-binding

解决方案


当输入的值为空时,将显示占位符。由于小数始终具有默认值,因此不能为空。将模型上的属性类型更改为Postage可为空的小数将解决此问题。

试试下面的代码看看有什么不同。

HTML:

<div class="form-group">
    <label asp-for="Postage"></label>
    <div class="input-icon">
        <input type="number" class="form-control postageInput" placeholder="0.00" asp-for="Postage" />
        <i>£</i>
    </div>
</div>
<div class="form-group">
    <label asp-for="PostageNullable"></label>
    <div class="input-icon">
        <input type="number" class="form-control postageInput" placeholder="0.00" asp-for="PostageNullable" />
        <i>£</i>
    </div>
</div>

模型:

public decimal Postage { get; set; }

public decimal? PostageNullable { get; set; }

推荐阅读