必须的属性为DateTime的属性 [英] Required Attribute for DateTime property

查看:121
本文介绍了必须的属性为DateTime的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了下面code作出指定的日期为必填字段。但是,当删除默认的日期,并尝试提交,没有显示任何错误消息。

I've wrote the below code for making appointed date as required field. But when remove the default date and try to submit, no error message is shown.

[DisplayName("Appointed Date")]
[Required(ErrorMessage = "Appointed Date Is Required")]
public virtual DateTime AppointedDate { get; set; }

请让我知道,如果我需要做任何事情了。

Please let me know, if i need to do anything more.

推荐答案


通常,这与非可空类型在解析模型绑定没有做。制作日期为空的模型,看看是否能解决您的问题。否则,写自己的模型绑定和处理这更好的。

Usually this has to do with non-nullable types failing in the model binder on parsing. Make the date nullable in the model and see if that solves your problem. Otherwise, write your own model binder and handle this better.

编辑:和机型的我的意思是视图的视图模型,使推荐的变化,如果你想坚持的观点(这我假设是使用EF)绑定到你的模型,按照写自己的模型绑定建议

And by model I mean a view model for the view, to make the recommended change, if you want to stick with binding to your model in the view (which I am assuming is using EF), follow the write your own model binder suggestion

编辑2:我们做了这样的事情得到一个自定义格式的可空的日期时间解析(这可能是一个良好的开端,为您调整为一个非可空类型):

Edit 2: We did something like this to get a custom format to parse in a nullable datetime (which might be a good start for you to tweak for a non-nullable type):


public sealed class DateTimeBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }

        if (bindingContext == null)
        {
            throw new ArgumentNullException("bindingContext");
        }

        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

        if (valueProviderResult == null)
        {
            return null;
        }

        var attemptedValue = valueProviderResult.AttemptedValue;

        return ParseDateTimeInfo(bindingContext, attemptedValue);
    }

    private static DateTime? ParseDateTimeInfo(ModelBindingContext bindingContext, string attemptedValue)
    {
        if (string.IsNullOrEmpty(attemptedValue))
        {
            return null;
        }

        if (!Regex.IsMatch(attemptedValue, @"^\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$", RegexOptions.IgnoreCase))
        {
            var displayName = bindingContext.ModelMetadata.DisplayName;
            var errorMessage = string.Format("{0} must be in the format DD-MMM-YYYY", displayName);
            bindingContext.ModelState.AddModelError(bindingContext.ModelMetadata.PropertyName, errorMessage);
            return null;
        }

        return DateTime.Parse(attemptedValue);
    }
}

然后(在你的依赖注入容器提供此类)注册该带:

Then register this with (by providing this class in your Dependency Injection container):


public class EventOrganizerProviders : IModelBinderProvider
{
    public IModelBinder GetBinder(Type modelType)
    {
        if (modelType == typeof(DateTime))
        {
            return new DateTimeBinder();
        }

                // Other types follow
        if (modelType == typeof(TimeSpan?))
        {
            return new TimeSpanBinder();
        }

        return null;
    }
}

这篇关于必须的属性为DateTime的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆