20

I am using Entity Framework (v4) entities. I have an entity called Car with a Year property of type integer. The Year property does not allow NULL. I have the following in my Create view:

<%= Html.TextBoxFor(model => model.Year) %>

I am required to return a new Car object (due to other requirements) in my HttpGet Create action in the CarController.

Currently, a zero is displayed in the Year textbox because the Year property does not allow NULL. I would like to display an empty textbox in the Create view. How do I do this?

thd
  • 2,023
  • 7
  • 31
  • 45

4 Answers4

51

Use Html Attributes Overload. In razor it would be:

@Html.TextBoxFor(model => model.Year, new { Value = "" })
nabeelfarid
  • 4,156
  • 5
  • 42
  • 60
  • 18
    It's also important to note that "Value" must have a capital "V" for this to work, but this is the best solution. – blockloop Aug 22 '12 at 21:14
  • 4
    As I also commented on a similar answer in one of the linked questions... It should be noted that this doesn't work well when used with typical MVC server-side validation where you redisplay the view with the validation errors (Ex; `if(!ModelState.IsValid) return View(viewmodel)`). Anytime the textbox is rendered at page load, it's going to display an empty string. This is great for regular first-time rendering of the page, but bad when the user is coming back due to validation failing. Whatever data they entered in the fields will be lost and replaced with the empty string. – EF0 May 16 '14 at 21:19
1

Try this instead:

Html.TextBox("Year", "")
Cristi Todoran
  • 519
  • 3
  • 5
0

If you are using the strongly typed TextAreaFor helper, then there is no direct way to set a default value. The point of the strongly typed helper is that it binds the text area to a model property and gets the value from there. If you want a default value, then putting in the model would achieve that. You can also just switch to the non-strongly typed TextArea helper. It gives you more a bit more flexibility for cases like this:

   @{
          var defaultValue= "";
        }
    @Html.TextArea("Model.Description", defaultValue, new { Value = "added text", @class = "form-control", @placeholder = "Write a description", @rows = 5 })
Krishna Soni
  • 95
  • 1
  • 9
-1

Try this is you are trying to append to your field or want to modify an existing field with an empty TextBoxFor.

Html.TextBoxFor(model => model.Year, Model.Year="")
Konrad Krakowiak
  • 12,285
  • 11
  • 58
  • 45