Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

c# - Html.TextboxFor default value for Integer/Decimal to be Empty instead of 0

I am using the default asp.net MVC 2 syntax to construct TextBox's which are integer or decimal for my asp.net MVC web app:

<%: Html.TextBoxFor(model => model.Loan.InterestRate) %>

pretty straight forward, but the problem is inherently of the fact my binding model objects are decimal or int and non-nullable, they print their value as zero (0) on page load if my model is empty (such as in add mode for a CRUD template) and zero is an incorrect value and is invalid for my page validation also.

How could I have textboxes which have no starting value, just an empty textbox, I understand zero is a potential value, but I only accept values greater than zero anyway, so this is not a problem for me.

I even tried casting as a nullable decimal and also a non-for helper (which is not ideal), but alas, I am still receiving the default '0' value. any ideas??

<%: Html.TextBox("Loan.InterestRate", Model.Loan.InterestRate == 0 ? 
    (decimal?)null : Model.Loan.InterestRate) %>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your model add DisplayFormat attribute

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.#}")]  
decimal  InterestRate { get; set; }

View

@Html.TextBoxFor(model => model.InterestRate)

This outputs empty instead of 0. More format examples here

Update

TextBoxFor does`s not works with format, but EditorFor does:

@Html.EditorFor(model => model.InterestRate)

Update 2

It does work for TextBoxFor this way:

@Html.TextBoxFor(model => model.InterestRate, "{0:#.#}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...