4

I know that you can create a textbox using ASP.NET that will automatically be filled with whatever the value in the model is by using

<%: Html.TextBoxFor(model => model.FirstName, new { id = "FirstName", placeholder = "[First Name]" }) %>

Is there a way to give it a default value if model.FirstName is null?

I've tried adding a value attribute, but that didn't work.

I also can't pass in a model with that value included, because it will affect other areas of the form.

tereško
  • 58,060
  • 25
  • 98
  • 150
Alex
  • 1,042
  • 3
  • 13
  • 32
  • 1
    same idea. however, as I stated in my question, I tried both the top voted answer, and the accepted answer, and neither worked. – Alex May 07 '12 at 16:23

2 Answers2

11

You could change the model property to return a default value if it's null (or setting default values when creating the model) or you can use the Html.TextBox helper instead of Html.TextBoxFor:

<%: Html.TextBox("FirstName", Model.FirstName ?? "The default value", new { id = "FirstName", placeholder = "[First Name]" }) %>

or use the value-attribute:

<%: Html.TextBoxFor(model => model.FirstName, new { @Value = "The default value", id = "FirstName", placeholder = "[First Name]" }) %>
Mario S
  • 11,715
  • 24
  • 39
  • 47
-1

Would something like a watermark work for what you're trying to accomplish?

There are a number of different implementation for jquery - this looks like it would work, and there is an option to use the title attribute for the watermark, which could be part of your model.

chris
  • 36,094
  • 53
  • 157
  • 237