Matt Hooper
Matt Hooper

Reputation: 113

How to display an empty textbox if the value equals zero?

I have a simple view in which I use an HTML Helper to generate a text input :

@Html.TextBox("Something",Model.myObject.myValue)

myValue is a float.

If myValue==0, I don't want to display 0. Is it possible, and how ?

Thanks !

Upvotes: 0

Views: 1519

Answers (2)

phuzi
phuzi

Reputation: 13060

How about just adding a quick check?

@Html.TextBox("Something", Model.myObject.myValue == 0 ? string.Empty : Model.myObject.myValue.ToString())

Upvotes: 2

David
David

Reputation: 218877

You could just use a simple inline conditional when setting the value:

@Html.TextBox("Something", Model.myObject.myValue == 0 ? "" : Model.myObject.myValue.ToString())

Conversely, it might be cleaner to do this in the model itself. You can add a calculated property to the model definition:

public string MyNonZeroValue
{
    get { return myObject.myValue == 0 ? "" : myObject.myValue.ToString(); }
}

Then just bind to that model property:

@Html.TextBox("Something", Model.MyNonZeroValue)

Upvotes: 5

Related Questions