Sara
Sara

Reputation: 131

ASP.Net MVC 2 - Need To Add A Default Property To A Strongly Typed Html.Textbox Helper In Asp.Net MVC 2

I'm having a problem with something that I'm sure is very simple. I have been using Asp.Net MVC and I decided to start using Asp.Net MVC 2. Something has changed and now I need a little help. The strongly typed helpers are now written like this -

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

I need to add a default value to a textbox. In the prior version of Asp.Net MVC it was easy to assign a default value. I thought doing the following would work in MVC 2-

<%= Html.TextBoxFor(model => model.CountyId, new{ value = 840 })%>

This, however, does not work for me in Asp.Net MVC 2. The value is still blank for the textbox. I want to make sure that this isn't some random error that I am having. Has anyone else encountered the same problem? I have searched and searched to find more information on the default property for the html helpers in MVC 2, but I can't find anything. Does anyone out there know how to correctly assign a default value to a textbox in Asp.Net MVC 2?

Upvotes: 6

Views: 5585

Answers (4)

Syed
Syed

Reputation: 21

@Html.TextBoxFor(model => model.CountyId, new{ @value = 840 })

works in asp.net mvc3 razor syntax

Upvotes: 1

dannie.f
dannie.f

Reputation: 2425

Actually, in case anyone else has this problem, using Value instead of value works. I think the issue is that value with a common v is a c# keyword.

Upvotes: 9

Sara
Sara

Reputation: 131

OK. I have found the answer to my problem - sort of. The new Html.TextBoxFor in MVC 2 doesn't allow the setting of the value property using the object htmlattributes even though it retains the ability to set all of the other properties using this syntax-

<%= Html.TextBoxFor(model => model.CountryName, new { maxlength = "40" })%>

So to get around this issue, if you need to set a default value on a textbox field, you need to use the old syntax -

<%= Html.TextBox("CountryName", "Enter your country name")%>

That will add a default value property appropriately in the html. The new TextBoxFor specification can't be used in this instance, but the value will still be returned back to the controller in the same way as the lambda expression. ALL of the other properties of the textbox can be set using textboxfor (maxlength, etc.) using the new { whateverProperty = value } syntax - just not the value property.

Upvotes: 3

Dan Diplo
Dan Diplo

Reputation: 25339

If it's a constant value you could assign the default value to the property in your model instead (you can set it in your constructor or in a backing field if you use 'old-style' properties). Something like:

public class Model
{
   public int CountryId { get; set; }

   public Model()
   {
      this.CountryId = 840;
   }
}

Or if it varies per request, then set it in a View Model that you pass to your view from your controller.

Upvotes: 5

Related Questions