I have an input field in which a user would type in a price. I want there to be a placeholder of 0.00
.
The placeholder only works if I remove model binding: asp-for="Postage"
Why is this happening? and how do I display the placeholder?
HTML input field:
@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>
The Model:
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...]
}
CodePudding user response:
The placeholder is shown when the value of the input is empty. Since a decimal always has a default value, it can't be empty. Changing the type of the Postage
property on the model to a nullable decimal will fix this.
Try the code below to see the difference.
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>
Model:
public decimal Postage { get; set; }
public decimal? PostageNullable { get; set; }