Anthony
Anthony

Reputation: 2824

Make Html.TextBoxFor show non-initialized integer property as empty string in MVC 4

I have added Html.TextBoxFor to my view:

@Html.TextBoxFor(x => x.zip, String.Empty, new { @class = "gsTextBox", placeholder = "Enter your zip" });

And it shows 0 in the input instead of empty string.

I also have found this solution, but it seems to be horrible. Or this is nice approach? Or maybe I should replace 0 by empty string using javascript?

Upvotes: 1

Views: 4033

Answers (3)

Omid Marofpor
Omid Marofpor

Reputation: 1

if you Wont change your Model by Nullable Property:

Use javascrip or Jquery Way.

$("input.no-init").val("");

Upvotes: 0

VictorySaber
VictorySaber

Reputation: 3164

Alternatively, if you do not want to have to use nullables:

@Html.TextBoxFor(x => x.zip, new { placeholder = "Enter your zip", @class = "gsTextBox", @Value = (Model.zip > 0 ? Model.zip.ToString() : string.Empty) })

The empty string will cause the placeholder to appear. In the event of a validation error or similar and returning to the page, this code will show the value the user entered... or the placeholder if not greater than 0.

Upvotes: 3

ssilas777
ssilas777

Reputation: 9764

Try this - Make int nullable

public int? zip { get;set; }

Upvotes: 4

Related Questions