How to set default value for text field Html.TextBoxFor (...)?

I know that you can create a text field using ASP.NET that will be automatically populated with any value in the model 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 null?

I tried to add the value attribute, but that didn't work.

I also can’t pass the model with the value turned on, because it will affect other areas of the form.

+4
source share
2 answers

You can change the model property to return the default value if it is null (or sets default values ​​when creating the model), or you can use the helper Html.TextBox 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]" }) %> 
+11
source

Will something like a watermark work on what you are trying to accomplish?

There are several different implementations for jquery - this looks like it will work, and it is possible to use the title attribute for the watermark, which may be part of your model.

-1
source

Source: https://habr.com/ru/post/1411146/


All Articles