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

后端 未结 4 1977
逝去的感伤
逝去的感伤 2020-12-18 20:41

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

public class RegisterModel
{
    [Display(Name = \"User name\")]
    [Re         


        
相关标签:
4条回答
  • 2020-12-18 20:48

    ReadOnly attribute doesn't block the HMTL helper to display the field as an enabled input. It is an information that the only the MVC data Binder will respect.

    It means that RegisterModel instance, which will be posted back after form submission by a user, will always has null value on it's UserName property, regardless of user's input in the appropriate field of the form.

    0 讨论(0)
  • 2020-12-18 20:49

    [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

    0 讨论(0)
  • 2020-12-18 20:53

    If you're using a SETTER you have to use { get; private set; }. That will make it so the client can't change the value. You can also just use an HTML 5 input and mark it there.

    0 讨论(0)
  • 2020-12-18 21:07

    ReadOnly attribute does not set the input to read-only.

    Try this

    Html.TextBoxFor(x => x.UserName, new { readonly = "readonly" })
    
    0 讨论(0)
提交回复
热议问题