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

C#.Netasp.net Mvc

C# Problem Overview


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) %>

C# Solutions


Solution 1 - C#

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:#.#}")

Solution 2 - C#

I use this solution :

   @Html.TextBoxFor(model => model.Year, new { Value = "" })

refer to : https://stackoverflow.com/a/6186576/297487

Solution 3 - C#

You can override the default template by putting a custom template in /Shared/EditorTemplates or by controller in /ControllerName/EditorTemplates.

I use this one for Int's. Its named Int32.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%
    string displayText = string.Empty;

    if (Model != null)
    {
        displayText = Model.ToString();
    }
    
%>

<%= Html.TextBox("", displayText)%>

Solution 4 - C#

Another one could be to check the value

@Html.TextBoxFor
(m => m.CertificateID, new { @Value = (Model.CertificateID > 0 ?Model.CertificateID.ToString() :string.Empty) })

Solution 5 - C#

What about "" instead of null.

    <%: Html.TextBox("Loan.InterestRate", 
Model.Loan.InterestRate == 0 ?     "" : Model.Loan.InterestRate) %>

Also why isnt Loan.InterestRate nullable?

<%: Html.TextBox("Loan.InterestRate", Model.Loan.InterestRate ?? "") %>

Solution 6 - C#

An alternative solution is to use jQuery to replace zeros with empty string when the page loads. Choose any name to use as a class name for all input fields which should be populated with empty string instead of zero. For example non-zero-num.

@Html.TextBoxFor(model => model.InterestRate, new { @class = "non-zero-num" }) 

And add the following script on your page:

<script>
    $(document).ready(function(){
        $(".non-zero-num").val($(this).val() == 0 ? '' : $(this).val());
    })
</script>

Solution 7 - C#

I think @jfar's answer points in the right direction but the Int32.ascx should be this

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Int32>" %>
<%
    string displayText;

    if (Model == 0)
    {
        displayText = "";
    }
    else
    {
        displayText = Model.ToString();
    }

%>  

<%= Html.TextBox("", displayText)%>

or updated answer using Razor (/Shared/EditorTemplates/Int32.cshtml)

@model Int32
@{
    string text = Model == 0 ? "" : Model.ToString();
}
@Html.TextBox("", text)

Solution 8 - C#

Here is what you can do: (VB Code)

This is the core:

@IIf(Model.YourNumericValue = 0, "", Model.YourNumericValue)

Here is if you use the HTML to render your textbox

<input type="text" name="sYourTextboxName"  value="@IIf(Model.YourNumericValue= 0, "", Model.YourNumericValue))">

Here is if you use HTML helper to render you textbox

 @Html.TextBox("sYourTextboxName", IIf(Model.YourNumericValue= 0, "", Model.YourNumericValue))

IIf is a very handy one line feature - the way it works is this.

IIf(Expression, TruePart, FalsePart)

So basically you saying - if my Parameter = 0 - I want to output nothing, String.Empty, Null, "" - and for the false part - it is like - oh if my Parameter does not equal to 0 - then that must be something other than 0 - so I will output the my numeric value without worrying that the zero will be in the textbox.

Or however you want to structure it.

Hope that helped!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGONealeView Question on Stackoverflow
Solution 1 - C#SelView Answer on Stackoverflow
Solution 2 - C#KhosroView Answer on Stackoverflow
Solution 3 - C#John FarrellView Answer on Stackoverflow
Solution 4 - C#SandeepView Answer on Stackoverflow
Solution 5 - C#bleevoView Answer on Stackoverflow
Solution 6 - C#MajixView Answer on Stackoverflow
Solution 7 - C#Dr BlowhardView Answer on Stackoverflow
Solution 8 - C#Alexey ShevelyovView Answer on Stackoverflow