views:

60

answers:

2

I have found hints that MVC 2 recognises the 'buddy class' type of property metadata, where data annotation attributes are applied to a 'buddy' metadata class, and the MetadataType on the actual entity class points to that buddy class, as below. However, as below, it seems the only attribute that makes any difference to the rendered UI is DisplayName. Why are the other attributes like DataType, Required, and ReadOnly not working? I.e. why can I enter text in a read only field? Why do I not get an error when a required field is empty? Why does the DataType attribute have no apparent effect? Why does EditorForModel not include validation messages?

[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
    public class CustomerMetadata
    {
        [ScaffoldColumn(false)]
        public object CustomerId { get; set; }

        [DisplayName("CustomerNo.")]
        [ReadOnly(true)]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Customer No. is required.")]
        public object CustomerNo { get; set; }
    }
}

I find behaviour the same whether I use an explicit LabelFor and TextBoxFor for each model property, or a single EditorForModel for the whole model.

+1  A: 
  1. Required only affects validation.
  2. Readonly only affects binding.

The ErrorMessage string is only output when you use the ValidationFor() method.

BuildStarted
@BuildStarted, EditorForModel is supposed to include validation.
ProfK
By default EditorForModel includes validation messages just fine. Making them `object` though the template doesn't know quite what to do with them. Change your `CustomerNo` to a `string` and see if it works for you then. (Both metadata and customer object)
BuildStarted
A: 

Because I was including an EnableClientValidation() call in my view, I was expecting these attributes to cause client side, Javascript validation to be performed, and validation messages to be displayed.

It turns out that merely including EnableClientValidation() is not alone enough, and one also has to modify the master page (or view if you're not using a master page), to include the following scripts:

<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>

I'm not sure the jQuery is required for validation or not, but I included it as advised and things work properly now.

ProfK