Applying CSS Class To Html.TextBoxFor

Working with the Asp .Net MVC application we use a lot of HtmlHelper(s). While using this helpers, we might want to apply some styling attribute to our components. In this short blog post we will see how we can apply CSS class while using Html.TextBoxFor HtmlHelper.

To look at the example, we will continue with our WhiteLabel solution we built in one of our previous blog post. Again, we have a model class let's say Asset and we want to apply a CSS class when we use Html.TextBoxFor HtmlHelper.

Make Html.TextBoxFor ReadOnly In Asp .Net MVC

While working with Asp .Net MVC applications, you come across a need to make a specific field ReadOnly. Prior to Asp .Net MVC when we worked with Asp .Net, making a TextBox readonly was as simple as marking the ReadOnly property to True.

With MVC things are bit different. We use HtmlHelper provided by Asp .Net MVC Framework to generate fields for our form. The HtmlHelper we use to create the input field is @Html.TextBoxFor.

Let's see how we can mark our input field as ReadOnly using this Helper. To demonstrate this I will be using the WhiteLabel solution I have built in one of my previous blog post.

With that solution with me, let's say I have a Model class Asset and following is the Form that takes user input for this Model class. Notice the Html.TextBoxFor HtmlHelper in the screen shot.

Asp .Net MVC DataAnnotation Range Attribute

So far, we have looked at a few DataAnnotation attributes namely, Required, Compare and Display. Following are the links to these blogs posts.

In this short blog post we will look at another important DataAnnotaion attribute, [Range].

Along with all the other Asset details, let's say we want to capture the Year in which the asset was purchased. We can simply add a new property in our model and Modify the View to have a new input field. However we have a requirement that value for this field must be between certain range.

This is the very good example to utilize yet another DataAnnotation attribute named Range. As the name suggest this attribute helps us validate user input between certain range. The first parameter of this attribute is the Minimum possible value and the second parameter is the Maxmimum possible value for the field.

Let's go ahead and make changes to our Model class so that it looks something like below.

Asp .Net MVC DataAnnotation Display Attribute

So far, we have looked at the two DataAnnotation attributes, [Required] and [Compare]. Following are the links to these topics in case you have missed them.

In this short blog post we will look at another important DataAnnotaion attribute, [Display].

So far, when we created our forms using the @Html.LabelFor HtmlHelper our Create Asset screen looked something like this.