MVC3 EditorFor readOnly

asp.net Mvc-3ReadonlyEditorfor

asp.net Mvc-3 Problem Overview


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.

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

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 - asp.net Mvc-3

This code is supported in MVC4 onwards

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

Solution 3 - asp.net Mvc-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

Solution 4 - asp.net Mvc-3

You can do it this way:

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

Solution 5 - asp.net Mvc-3

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

Solution 6 - asp.net Mvc-3

Try using:

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

Solution 7 - asp.net Mvc-3

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.

Solution 8 - asp.net Mvc-3

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

Solution 9 - asp.net Mvc-3

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

Solution 10 - asp.net Mvc-3

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

Solution 11 - asp.net Mvc-3

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

Solution 12 - asp.net Mvc-3

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

for example:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionwholee1View Question on Stackoverflow
Solution 1 - asp.net Mvc-3danludwigView Answer on Stackoverflow
Solution 2 - asp.net Mvc-3GSoft ConsultingView Answer on Stackoverflow
Solution 3 - asp.net Mvc-3SeichiView Answer on Stackoverflow
Solution 4 - asp.net Mvc-3FrancoisView Answer on Stackoverflow
Solution 5 - asp.net Mvc-3stovrozView Answer on Stackoverflow
Solution 6 - asp.net Mvc-3Mohamed AshrafView Answer on Stackoverflow
Solution 7 - asp.net Mvc-3Serj SaganView Answer on Stackoverflow
Solution 8 - asp.net Mvc-3DaniilZView Answer on Stackoverflow
Solution 9 - asp.net Mvc-3da_jokkerView Answer on Stackoverflow
Solution 10 - asp.net Mvc-3john blairView Answer on Stackoverflow
Solution 11 - asp.net Mvc-3Luís PoncianoView Answer on Stackoverflow
Solution 12 - asp.net Mvc-3MaTyaView Answer on Stackoverflow