MVC3 EditorFor readOnly
Solution 1:
The EditorFor html helper does not have overloads that take HTML attributes. In this case, you need to use something more specific like TextBoxFor:
<div class="editor-field">
@Html.TextBoxFor(model => model.userName, new
{ disabled = "disabled", @readonly = "readonly" })
</div>
You can still use EditorFor, but you will need to have a TextBoxFor in a custom EditorTemplate:
public class MyModel
{
[UIHint("userName")]
public string userName { ;get; set; }
}
Then, in your Views/Shared/EditorTemplates folder, create a file userName.cshtml. In that file, put this:
@model string
@Html.TextBoxFor(m => m, new { disabled = "disabled", @readonly = "readonly" })
Solution 2:
This code is supported in MVC4 onwards
@Html.EditorFor(model => model.userName, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", @readonly = "readonly" } })
Solution 3:
For those who wonder why you want to use an EditoFor if you don`t want it to be editable, I have an example.
I have this in my Model.
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0: dd/MM/yyyy}")]
public DateTime issueDate { get; set; }
and when you want to display that format, the only way it works is with an EditorFor, but I have a jquery datepicker for that "input" so it has to be readonly to avoid the users of writting down wrong dates.
To make it work the way I want I put this in the View...
@Html.EditorFor(m => m.issueDate, new{ @class="inp", @style="width:200px", @MaxLength = "200"})
and this in my ready function...
$('#issueDate').prop('readOnly', true);
I hope this would be helpful for someone out there. Sorry for my English