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

♀尐吖头ヾ 提交于 2019-11-28 02:39:18

问题


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?


回答1:


[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




回答2:


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.




回答3:


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

Try this

Html.TextBoxFor(x => x.UserName, new { readonly = "readonly" })



回答4:


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.



来源:https://stackoverflow.com/questions/14995577/readonly-attribute-doesnt-work-in-asp-net-mvc-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!