TJK
TJK

Reputation: 441

make Html.Editorfor field readonly in mvc3

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

Upvotes: 3

Views: 18811

Answers (4)

Gilberto B. Terra Jr.
Gilberto B. Terra Jr.

Reputation: 313

I use to show read-only information this way:

@Html.DisplayFor(model => model.CadastradoEm, new { @class = "form-control" })
@Html.HiddenFor(model => model.CadastradoEm)

You need to include a hidden input in addition to the display text, cause DisplayFor() doesn't generate a control that posts back ;)

Upvotes: 0

mzoabi
mzoabi

Reputation: 369

You can use:

@Html.DisplayFor()

Upvotes: 3

Oladipo Olasemo
Oladipo Olasemo

Reputation: 2042

Decorate the property with the [HiddenInput] Attribute from the System.Web.Mvc namespace.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039528

<%= 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
    ) %>
    

Upvotes: 5

Related Questions