make Html.Editorfor field readonly in mvc3

TJK picture TJK · Sep 18, 2011 · Viewed 18.7k times · Source

I am using this, an editor template (located in the Shared\EditorTemplates folder in my solution)

  <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
  <%=Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), ViewData )%>

and this in my view

  @Html.EditorFor(model => model.ModifiedDate)

how to make this field readonly in the view

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 18, 2011
<%= Html.EditorFor(x => x.ModifiedDate, new { @readonly = "readonly" }) %>

UPDATE:

OK, now that you sent me the sample project here are the issues:

  1. You have a spelling mistake in the ~/Views/Shared/EditorTempletes folder. It should be ~/Views/Shared/EditorTemplates.
  2. You editor template must be called DateTime.ascx and not a DateTime.aspx. And because of this the header must look like this (use <%@ Control ... instead of <%@ Page ...):

    <%@ Control 
        Language="C#" 
        Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" 
    %>
    <%= Html.TextBox(
        "", 
        (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), 
        ViewData
    ) %>