user217648
user217648

Reputation: 3466

decimal type property adds a zero to the textbox

I have a MVC4 application, type of one of properties is decimal, when it loads the view it adds a zero to the textbox.

How can I make the textbox to be empty when it loads first time?

    [DataType(DataType.Currency)]
    [Column(TypeName = "money")]
    [Display(Name ="Amount")]
    [Required(ErrorMessage = "You must add amount")]
    public decimal Amount { get; set; }

   @Html.TextBoxFor(model => model.Amount, new { @class = "form-control" })

Thanks.

Upvotes: 1

Views: 876

Answers (1)

Tommy
Tommy

Reputation: 39807

This is showing a zero the first time is loads because you are not populating the model with anything. So, the ViewEngine inserts the "default" value of a decimal type, which is a zero.

To make it not show anything, you would need to make your decimal property nullable.

[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name ="Amount")]
[Required(ErrorMessage = "You must add amount")]
public decimal? Amount { get; set; }

Now, the view engine will see the default as null and create an empty textbox.

Upvotes: 3

Related Questions