Make Html.TextBoxFor ReadOnly In Asp .Net MVC

Jun 22, 2013


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.

TextBoxFor HtmlHelper

We will pass this readonly attribute and it's value in the overloaded method of TextBoxFor HtmlHelper

Go ahead and run the application. Once the page is examine the rendered HTML of our input for AssetName property.

TextBoxFor HtmlHelper

Notice the readonly=true attribute appended to the HTML of the field.

Note

Sometimes when you are using MVC scaffolding, it uses @Html.EditorFor to generate the input box. However we can not use it for our scenario because it does not contain any overloaded methods to pass this extra Html attribute. So, you can make @Html.EditorFor ReadOnly input field.