Using Editable attribute on MVC 3 view model

后端 未结 5 1716
故里飘歌
故里飘歌 2020-12-10 05:58

I\'m looking to use attributes to mark view model properties as readonly so that the view fields are read only in the rendered view. Applying System.ComponentModel.DataAnnot

5条回答
  •  一整个雨季
    2020-12-10 06:27

    The EditableAttribute documentation states:

    The presence of the EditableAttribute attribute on a data field indicates whether the user should be able to change the field's value.

    This class neither enforces nor guarantees that a field is editable. The underlying data store might allow the field to be changed regardless of the presence of this attribute.

    Unfortunately, this means that the use of this attribute doesn't have any effect on validation in MVC. This feels wrong but it makes sense if you think about what it would take to implement in the MVC framework. For instance, in a typical "Edit" view, the user does an initial GET request where the Model is populated (usually from a DB record) and given to the View to be rendered to the user. Then the user makes some edits and then submits the form. Submitting the form causes a new instance of the Model to be constructed from the POST parameters. It would be very difficult for the validators to ensure the field has the same value in both object instances, because one of the instances (the first one from the GET request) has already been disposed of.

    Well if the Attribute has no functionality, why even bother to use it?

    My best guess is that they expect developers to use it in their code to show intent. More practically, you can also write your own custom code to check for the presence of this Attribute...

    AttributeCollection attributes = TypeDescriptor.GetAttributes(MyProperty);
    if (attributes[typeof(EditableAttribute)].AllowEdit)
    {
       // editable
    }
    else
    {
       // read-only
    }
    

    Also keep in mind that these DataAnnotation attributes are not only for MVC applications, they can be used for many different types of applications. Even though MVC doesn't do anything special with this Attribute, other frameworks have implemented functionality/validation for this attribute.

提交回复
热议问题