[asp.net-mvc-3] MVC3 EditorFor readOnly

I want to make readOnly with EditorFor in edit page.

I tried to put readonly and disabled as:

<div class="editor-field">
        @Html.EditorFor(model => model.userName, new { disabled = "disabled", @readonly = "readonly" })
    </div>

However, it does not work. How can I make to disable edit this field?

Thank you.

This question is related to asp.net-mvc-3 readonly editorfor

The answer is


Try using:

@Html.DisplayFor(model => model.userName) <br/>
@Html.HiddenFor(model => model.userName)

Here's how I do it:

Model:

[ReadOnly(true)]
public string Email { get { return DbUser.Email; } }

View:

@Html.TheEditorFor(x => x.Email)

Extension:

namespace System.Web.Mvc
{
    public static class CustomExtensions
    {
        public static MvcHtmlString TheEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
        {
            return iEREditorForInternal(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        }

        private static MvcHtmlString iEREditorForInternal<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
        {
            if (htmlAttributes == null) htmlAttributes = new Dictionary<string, object>();

            TagBuilder builder = new TagBuilder("div");
            builder.MergeAttributes(htmlAttributes);

            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);


            string labelHtml = labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString();

            if (metadata.IsRequired)
                labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression, new { @class = "required" }).ToHtmlString();


            string editorHtml = Html.EditorExtensions.EditorFor(htmlHelper, expression).ToHtmlString();

            if (metadata.IsReadOnly)
                editorHtml = Html.DisplayExtensions.DisplayFor(htmlHelper, expression).ToHtmlString();


            string validationHtml = Html.ValidationExtensions.ValidationMessageFor(htmlHelper, expression).ToHtmlString();

            builder.InnerHtml = labelHtml + editorHtml + validationHtml;

            return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
        }
    }
}

Of course my editor is doing a bunch more stuff, like adding a label, adding a required class to that label as necessary, adding a DisplayFor if the property is ReadOnly EditorFor if its not, adding a ValidateMessageFor and finally wrapping all of that in a Div that can have Html Attributes assigned to it... my Views are super clean.


<div class="editor-field">
        @Html.EditorFor(model => model.userName)
</div>

Use jquery to disable

<script type="text/javascript">
   $(document).ready(function () {
      $('#userName').attr('disabled', true);
     });
</script>

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 = "" } })

This code is supported in MVC4 onwards

@Html.EditorFor(model => model.userName, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", @readonly = "readonly" } })

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" } })
 }

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


i think this is simple than other by using [Editable(false)] attribute

for example:

 public class MyModel
    {
        [Editable(false)]
        public string userName { get; set; }
    }

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): enter image description here

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; }

You can do it this way:

@Html.EditorFor(m => m.userName, new { htmlAttributes = new { disabled = true } })

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to readonly

How to make readonly all inputs in some div in Angular2? how to set select element as readonly ('disabled' doesnt pass select value on server) How to make a input field readonly with JavaScript? Python read-only property MVC3 EditorFor readOnly Oracle - How to create a readonly user Access Database opens as read only Declare a const array How to implement a read only property Why can't radio buttons be "readonly"?

Examples related to editorfor

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer MVC3 EditorFor readOnly Html5 Placeholders with .NET MVC 3 Razor EditorFor extension? Html attributes for EditorFor() in ASP.NET MVC