I want to make readOnly with EditorFor in edit page.
I tried to put readonly and disabled as:
@Html.Editor
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" })
i think this is simple than other by using [Editable(false)] attribute
for example:
public class MyModel
{
[Editable(false)]
public string userName { get; set; }
}
I know the question states MVC 3, but it was 2012, so just in case:
As of MVC 5.1 you can now pass HTML attributes to EditorFor
like so:
@Html.EditorFor(x => x.Name, new { htmlAttributes = new { @readonly = "", disabled = "" } })
I use the readonly
attribute instead of disabled
attribute - as this will still submit the value when the field is readonly.
Note: Any presence of the readonly attribute will make the field readonly
even if set to false, so hence why I branch the editor for code like below.
@if (disabled)
{
@Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { @class = "form-control", @readonly = "" } })
}
else
{
@Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { @class = "form-control" } })
}
Old post I know.. but now you can do this to keep alignment and all looking consistent..
@Html.EditorFor(model => model.myField, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
Create an EditorTemplate for a specific set of Views (bound by one Controller):
In this example I have a template for a Date, but you can change it to whatever you want.
Here is the code in the Data.cshtml:
@model Nullable<DateTime>
@Html.TextBox("", @Model != null ? String.Format("{0:d}", ((System.DateTime)Model).ToShortDateString()) : "", new { @class = "datefield", type = "date", disabled = "disabled" @readonly = "readonly" })
and in the model:
[DataType(DataType.Date)]
public DateTime? BlahDate { get; set; }