Question

I used Database-First to generate a model class (EDMX file), and I want to validate using "MetadataType". I read solutions here but they didn't work for me.

Here is my code:

[MetadataType(typeof(MovieEntitiesMetaData))]
public partial class MovieEntities
{        
}

public class MovieEntitiesMetaData
{
    [DisplayFormat(DataFormatString = "{0:c}")]
    public Nullable<global::System.Decimal> PRICE { get; set; }
}

Is there anything missing here, or why did my solution did not work?

Était-ce utile?

La solution

Create a new file called MoviePartial.cs and place the following code inside it:

[MetadataType(typeof(MovieMetaData))]
public partial class Movie
{    
    internal sealed class MovieMetaData
    {
        [DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
        [Required(ErrorMessage = "Price is required")]
        public decimal? PRICE { get; set; }
    }
}

You also need to pass the Movie type to the view so that the data annotations can be wired up. If you have a custom view model the data annotations won't get in action.

In the Create/Edit view you must have:

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

In the Details view you must have:

@Html.DisplayFor(m => m.PRICE)

For more on this, just follow this nice step by step tutorial:

Validation with the Data Annotation Validators (C#)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top