Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ReadOnly(true) work with Html.EditorForModel?

Consider the following setup:

Model:

public class Product
{
    [ReadOnly(true)]
    public int ProductID
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }
}

View:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<MvcApplication4.Models.Product>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%= Html.EditorForModel() %>
</asp:Content>

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new Product
            {
                ProductID = 1,
                Name = "Banana"
            });
    }
}

There result is this: alt text

I was expecting that the ProductID property was not going to be editable via the ReadOnly(true) attribute. Is this supported? If not is there any way to hint ASP.NET MVC that some properties of my model are read-only? I would not like to just hide ProductID via [ScaffoldColumn(false)].

like image 584
Atanas Korchev Avatar asked Aug 18 '10 08:08

Atanas Korchev


3 Answers

I solved this problem by adding a UIHintAttribute to the property on my class of "ReadOnly".

[UIHint("ReadOnly")]
public int ClassID { get; set; }

Then I simply added a ~\Views\Shared\EditorTemplates\ReadOnly.ascx file to my project with this in it:

<%= Model %>

A really simple way to add custom templates, you could include formatting or whatever.

like image 57
pwhe23 Avatar answered Nov 13 '22 11:11

pwhe23


The ReadOnly and Required attributes will be consumed by the metadata provider but won't be used. If you want to get rid of the input with EditorForModel you'll need a custom template, or [ScaffoldColumn(false)].

For custom template ~/Views/Home/EditorTemplates/Product.ascx:

<%@ Control Language="C#" Inherits="ViewUserControl<Product>" %>

<%: Html.LabelFor(x => x.ProductID) %>
<%: Html.TextBoxFor(x => x.ProductID, new { @readonly = "readonly" }) %>

<%: Html.LabelFor(x => x.Name) %>
<%: Html.TextBoxFor(x => x.Name) %>

Also note that the default model binder won't copy a value into a property with [ReadOnly(false)]. This attribute won't influence the UI rendered by the default templates.

like image 9
Darin Dimitrov Avatar answered Nov 13 '22 12:11

Darin Dimitrov


<%@ Control Language="C#" Inherits="ViewUserControl<Product>" %>

<%: Html.LabelFor(x => x.ProductID) %>
<%: Html.TextBoxFor(x => x.ProductID, new { @readonly = true }) %>

<%: Html.LabelFor(x => x.Name) %>
<%: Html.TextBoxFor(x => x.Name) %>
like image 2
Dinesh Avatar answered Nov 13 '22 10:11

Dinesh