将数据从模型传递到自定义验证类

时间:2010-09-02 10:44:51

标签: c# .net asp.net-mvc asp.net-mvc-2

我有一个数据验证类,用于检查会议的开始日期是否在结束日期之前。

模型会自动传递需要验证的日期,但是我在传递需要验证的数据时遇到了一些困难。

这是我的验证课

sealed public class StartLessThanEndAttribute : ValidationAttribute
    {            
        public DateTime DateEnd { get; set; }

        public override bool IsValid(object value)
        {                
            DateTime end = DateEnd;
            DateTime date = (DateTime)value;

            return (date < end);
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
        }
    }

这是包含数据注释的类

[StartLessThanEnd(ErrorMessage="Start Date must be before the end Date")]
public DateTime DateStart { get; set; }

这是我的控制器

[HttpPost, Authorize]
    public ActionResult Create(Pol_Event pol_Event)
    {
        ViewData["EventTypes"] = et.GetAllEventTypes().ToList();

        StartLessThanEndAttribute startDateLessThanEnd = new StartLessThanEndAttribute();


        startDateLessThanEnd.DateEnd = pol_Event.DateEnd;


        if (TryUpdateModel(pol_Event))
        {
            pol_Event.Created_On = DateTime.Now;
            pol_Event.Created_By = User.Identity.Name;

            eventRepo.Add(pol_Event);
            eventRepo.Save();
            return RedirectToAction("Details", "Events", new { id = pol_Event.EventID });
        }

        return View(pol_Event);
    }

1 个答案:

答案 0 :(得分:3)

使用多个属性的验证属性应该应用于模型而不是单个属性:

[AttributeUsage(AttributeTargets.Class)]
public class StartLessThanEndAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var model = (MyModel)value;
        return model.StartDate < model.EndDate;
    }
}

[StartLessThanEnd(ErrorMessage = "Start Date must be before the end Date")]
public class MyModel
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}