Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReadOnly attribute doesn't work in ASP.NET MVC Models

I have marked a property as readonly in the model class, like this:

public class RegisterModel
{
    [Display(Name = "User name")]
    [ReadOnly(true)]
    public string UserName { get; set; }
    ...
}

and in my view:

@Html.EditorFor(m => m.UserName)

but when I run the application, the textbox is not readonly.

I know I can use html attributes in the view to make it readonly, but I would prefer if this can be done in the model class itself.

Can it be achieved?

like image 296
Edi Wang Avatar asked Feb 21 '13 06:02

Edi Wang


1 Answers

[Update] I don't think it is possible without new { @readonly = "readonly" }.Readonly property specifies whether the property this attribute is bound to is read-only or read/write. Details Here.

But you could try for Custom Helpers or try Using Editable instead Readonly on the model and use the metadata property in your View.

[Editable(false)]

I guess you have already looked into Does ReadOnly(true) work with Html.EditorForModel?

also a fine article odetocode.com

like image 112
Shubh Avatar answered Sep 30 '22 09:09

Shubh