开发者

ASP.Net Dynamic Data - DataType Validation

Dynamic Data question:

I have 2 fields of type Nullable<DateTime> on my model

When I use the insert form and enter a garbage string e.g. "sdfsdfas" for a date it gives me an ugly error message

Unable to convert input string ' rtgh' to type 'System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0,开发者_Go百科 Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

So I've created a MetaData Class as follows to try and get a more friendly error

[MetadataType(typeof(RuleMetadata))]
    public partial class Rule
    {
        public class RuleMetadata
        {


            [ScaffoldColumn(false)]
            public Guid RuleId;

            // tried this overload
            [DataType("Some error")]
            public Nullable<DateTime> ValidFrom;

            // tried this overload
            [DataType(DataType.Date)]
            public Nullable<DateTime> ValidTo;
        }
    }

But it is totally ignored and I get the ugly error as before

what am I doing wrong?


eventually done this by creating a CustomAttribute

Seems like overkill for a framework which is meant to autmate stuff for you

 [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    sealed class DateFormatAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            DateTime dt;
            return DateTime.TryParse(value.ToString(), out dt);
        }
    }

then applied the attribute to my MetaData Class

[DateFormat(ErrorMessage = "Valid From must be a valid date format")]
            public DateTime? ValidFrom;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜