How to create a readonly textbox in ASP.NET MVC3, With Razor view engine ? Is there an HTMLHelper method available to do that ?
Something like this ?
@Html.ReadOnlyTextBoxFor(m => m.userCode)
How to create a readonly textbox in ASP.NET MVC3, With Razor view engine ? Is there an HTMLHelper method available to do that ?
Something like this ?
@Html.ReadOnlyTextBoxFor(m => m.userCode)
You are welcome to make an HTML Helper for this, but this is simply just an HTML attribute like any other. Would you make an HTML Helper for a text box that has other attributes?
The solution with TextBoxFor is OK but if you don't want to see the field like EditBox stylish (it might be little confused for user) involve changes as follow:
1. Razor code before changes
2. After changes
Generally this solution disable filed against editing but shows value of it. There is no need for code-behind modifications.
You can use below code for creating a TextBox as read-only.
Method -1
Method -2
UPDATE: Now it's very simple to add html attributes to default editor templates. Means instead of doing this:
you simply can do this:
Benefits: You haven't to call
.TextBoxFor
etc. for templates. Just call.EditorFor
.While @Shark's solution works correctly and it is simple and useful, my solution (that I use always) is this one Create an
editor-template
that can handlesreadonly
attribute:EditorTemplates
in~/Views/Shared/
PartialView
namedString.cshtml
Fill the
String.cshtml
with this code:In model class, put the
[ReadOnly(true)]
attribute on properties which you want to bereadonly
.e.g.
Now you can use razor's default syntax simply:
The first one, renders a normal
text-box
like this:and the second, will render to;
You can use this solution for any type of data (
DateTime
,DateTimeOffset
,DataType.Text
,DataType.MultilineText
and so on). Just create aneditor-template
.with credits to the previous answer by @Bronek and @Shimmy
This is I have done the samething in ASP.NET Core
The first input is readonly and the second one passes the value to Controller and is hidden.Hope it will be useful for someone working with ASP.Net Core.