【问题标题】:HTML input field placeholder not displaying when binding input field to model将输入字段绑定到模型时不显示 HTML 输入字段占位符
【发布时间】:2021-12-14 18:24:14
【问题描述】:

我有一个输入字段,用户可以在其中输入价格。我希望有一个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...]
}

【问题讨论】:

  • 尝试将Postage的类型更改为decimal?decimal 始终有一个值(默认为 0.0),因此它永远不能为“空”。
  • @JackA。十进制不是 HTML 输入字段的有效类型。模型中 Postage 属性的类型已经设置为十进制。
  • 我指的是模型,而不是 HTML。将其更改为可为空的小数。
  • 我的错,我误会了。这行得通,非常感谢

标签: c# html asp.net-core razor-pages model-binding


【解决方案1】:

当输入值为空时显示占位符。由于小数始终具有默认值,因此不能为空。将模型上的 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; }

【讨论】:

    猜你喜欢
    • 2013-12-17
    • 2018-03-23
    • 2013-04-08
    • 2013-09-01
    • 2011-11-14
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多