Html.EditorFor<> equivalent for viewing read-only data?

37,735

Solution 1

I may be missing something but can't you just use Html.LabelFor?

Edit: May need to be a combination using Html.LabelFor and Html.DisplayFor

Solution 2

Use

<%= Html.DisplayFor(model => model.Property) %>

Or if you want to see a readonly(disabled) textbox

<%= Html.TextBoxFor(model => model.Property, new { disabled="disabled", @readonly = "readonly" })%>

Solution 3

You can use

Html.DisplayFor(...)

Documentation:

http://msdn.microsoft.com/en-us/library/system.web.mvc.html.displayextensions.displayfor.aspx

Solution 4

MVC 5, Bootstrap 3 example.

<div class="col-md-6">
    @Html.LabelFor(m => m.UserModel.company, htmlAttributes: new {@class = "control-label tc-label"})
    @Html.EditorFor(m => m.UserModel.company, new {htmlAttributes = new { disabled = "disabled", @readonly = "readonly", @class = "form-control col-md-6"}})
    @Html.ValidationMessageFor(m => m.UserModel.company, "", new {@class = "text-danger"})
</div>

Solution 5

I have a textbox control which is bound to a property of the Model. However, I have a JQueryUI slider which I am using to populate the value, rather than have the user edit it directly. Therefore, I want this value to be read-only, but still bound to the model. I cannot apply html attributes using Html.EditorFor(...), I can use the Html.TextboxFor(...) method. However, if I set the HTML "disabled" attribute to a value of "disabled" (as per zihotki's solution), then the MVC framework by default does not bind the value in the textbox back to the bound property on the model when posting back to the controller method (see Model Binding With Disabled Textbox). My solution was to use Html.TextboxFor and set only the readonly attribute,

@Html.TextBoxFor(model => model.MyProperty, new { @readonly = "readonly" })

and then include a CSS entry for input:readonly to grey the read-only boxes out:

input:read-only
{
    background-color: #E6E6E6;
}
Share:
37,735
StrictlySocial
Author by

StrictlySocial

Updated on July 09, 2022

Comments

  • StrictlySocial
    StrictlySocial almost 2 years

    I am currently using the Html.EditorFor<> method for generating editor fields, however I would like to use something similar for displaying field information in a read-only format such as a details page, i.e. a label with the field name followed by a label with the field value.

    Is there currently any equivalent in MVC for generating this? Or am I going to have to create a custom helper?

    Thanks in advance.

    Edit: I am aware of DisplayFor and LabelFor, is it just a case of manually having to combine these?