Problem with DataAnnotations in partial class

落爺英雄遲暮 提交于 2019-12-04 15:14:08

I tend to use Metadata classes as followed.

[MetadataType(typeof(FalalaMetadata))]
public partial class Falala
{
    public string Name { get; set; }

    public string Age { get; set; }
}
public class FalalaMetadata
{
    [Required(ErrorMessage="Falala requires name.")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Falala requires age.")]
    public string Age { get; set; }
}

Which works fine for me.

The following should also work (and is a better way to implement metadata classes):

[MetadataTypeAttribute(typeof(Falala.FalalaMetaData))]
public partial class Falala
{
    internal sealed class FalalaMetadata
    {
        [Required(ErrorMessage="Falala requires name.")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Falala requires age.")]
        public string Age { get; set; }
    }
}

I ran into a similar problem and finally got it working by putting both the Model class and the Metadata "buddy" class in the same namespace, even though my references seemed ok. I'm kind of a .net noob though so I'm not exactly comfortable with namespaces, could be something else.

Could Internal on the nested class be the reason...?

I had a similiar problem and it seemed to all boiled down to not making the individual fields in the nested metadata class public - wonder if making the whole class internal causes the same problem?

Tony Sebastian

Not sure if this help, but I had a similar problem and spend days on it. At the end it was just a minor change which did the trick for me.

I changed UnobtrusiveJavaScriptEnabled to false in the config file

Good luck

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