[英]Why MetadataType doesn't do my validation in database first approach?
I used Database-First to generate a model class (EDMX file), and I want to validate using "MetadataType". 我使用Database-First生成模型类(EDMX文件),我想使用“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? 这里有什么遗漏,或者为什么我的解决方案不起作用?
Create a new file called MoviePartial.cs
and place the following code inside it: 创建一个名为
MoviePartial.cs
的新文件,并在其中放置以下代码:
[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. 您还需要将
Movie
类型传递给视图,以便可以连接数据注释。 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#) 使用数据注释验证器进行验证(C#)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.