简体   繁体   English

如何将自定义验证规则应用于MVC3中的ViewModel属性

[英]How to apply Custom Validation rules to ViewModel attribute in MVC3

In my MVC application I have the following ViewModel : 在我的MVC应用程序中,我具有以下ViewModel

public class MyViewModel
{
   public int StartYear { get; set; }
   public int? StartMonth { get; set; }
   public int? StartDay { get; set; }

   public int? EndYear { get; set; }
   public int? EndMonth { get; set; }
   public int? EndDay { get; set; }

   [DateStart]
   public DateTime StartDate
   {
       get
       {
           return new DateTime(StartYear, StartMonth ?? 1, StartDay ?? 1);
       }
   }

   [DateEnd(DateStartProperty="StartDate")]
   public DateTime EndDate
   {
       get
       {
           return new DateTime(EndYear ?? DateTime.MaxValue.Year, EndMonth ?? 12, EndDay ?? 31);
       }
   }
 }

I do not use a calendar helper because I need the date in this format (there is a logic behind). 我不使用日历助手,因为我需要这种格式的日期(后面有逻辑)。 Now I created my Custom Validation rule: 现在,我创建了自定义验证规则:

    public sealed class DateStartAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            DateTime dateStart = (DateTime)value;
            return (dateStart > DateTime.Now);
        }
    }

    public sealed class DateEndAttribute : ValidationAttribute
    {
        public string DateStartProperty { get; set; }
        public override bool IsValid(object value)
        {
            // Get Value of the DateStart property
            string dateStartString = HttpContext.Current.Request[DateStartProperty];
            DateTime dateEnd = (DateTime)value;
            DateTime dateStart = DateTime.Parse(dateStartString);

            // Meeting start time must be before the end time
            return dateStart < dateEnd;
        }
    }

The problem is that DateStartProperty (in this case StartDate ) is not in the Request object since it is calculated after the form is posted to the server. 问题是DateStartProperty (在本例中为StartDate )不在Request对象中,因为它是在将表单发布到服务器后计算的。 Therefore the dateStartString is always null. 因此, dateStartString始终为null。 How can I get the value of StartDate ? 如何获得StartDate的值?

您可以使用反射来获得该答案中的其他属性(对我来说似乎有点不客气),也可以为该类创建自定义验证属性,而不是为此处讨论的单个属性创建属性。

Try this plugin: http://docs.jquery.com/Plugins/Validation/multiplefields . 试试这个插件: http : //docs.jquery.com/Plugins/Validation/multiplefields

Hope this helps~ 希望这会有所帮助〜

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM