2009-11-23 10 views
5

Ho un modello che utilizza DataAnnotations. Qualcosa comeErrorMessage viene ignorato in DataAnnotations DataType attributo

public class Appointment { 
    [Required(ErrorMessage="Please enter your name")] 
    public string Name { get; set; } 

    [Required(ErrorMessage="Please enter your appointment date?")] 
    [DataType(DataType.Date, ErrorMessage="Appointment date is not a date")] 
    public DateTime AppointmentDate { get; set; } 
} 

Gli attributi "Richiesto" rispettano il valore in ErrorMessage; cioè, se non inserisco un valore, ricevo il messaggio "please enter". Tuttavia, se entro una stringa nel campo DateTime, sto ottenendo un messaggio di errore di sistema standard "Il valore 'bla' non è valida per AppointmentDate".

Ho eseguito il debug tramite il codice MVC ASP.NET e sembra che nel caso di FormatException non scelga il nome visualizzato corretto da propertyMetadata. O quello, o mi manca qualcosa di evidentemente ovvio:/

Qualcuno ha incontrato questo problema? Sono io, o è solo beta (sto usando ASP.NET MVC 2 Beta)?

risposta

2

In MVC1 l'attributo DataType non fa quello che ci si aspetterebbe, sembra che non sia nemmeno in MVC2. La tua migliore chiamata è quella di avere una proprietà stringa che rappresenta la data, verificare che sia valida lì.

Ecco un piccolo estratto da un progetto (utilizzando DataAnnotations e xVal):

private List<ErrorInfo> _errors; 
     private List<ErrorInfo> Errors 
     { 
      get 
      { 
       if (_errors == null) 
        _errors = new List<ErrorInfo>(); 
       return _errors; 
      } 
      //set { _errors = value; } 
     } 

private string _startDateTimeString; 

     /// <summary> 
     /// A string reprsentation of the StartDateTime, used for validation purposes in the views. 
     /// </summary> 
     /// <remarks> 
     /// If the user passes something like 45/45/80 it would be a valid mm/dd/yy format, but an invalid date, 
     /// which would cause an InvalidOperationException to be thrown by UpdateModel(). By assigning dates to string properties 
     /// we can check not only the format, but the actual validity of dates. 
     /// </remarks> 
     public string StartDateTimeString 
     { 
      get 
      { 
       return _startDateTimeString; 
      } 
      set 
      { 
       // Check whether the start date passed from the controller is a valid date. 
       DateTime startDateTime; 
       bool validStartDate = DateTime.TryParse(value, out startDateTime); 
       if (validStartDate) 
       { 
        StartDateTime = startDateTime; 
       } 
       else 
       { 
        Errors.Add(new ErrorInfo("StartDateTime", "Provide a valid date for the start time.")); 
       } 

       _startDateTimeString = value; 
      } 
     } 

     partial void OnValidate(ChangeAction action) 
     { 
      if (action != ChangeAction.Delete) 
      { 
       Errors.AddRange(DataAnnotationsValidationRunner.GetErrors(this)); 

       if (StartDateTimeString != null) 
       { 
        DateTime startDateTime; 
        if (!DateTime.TryParse(StartDateTimeString, out startDateTime)) 
        { 
         Errors.Add(new ErrorInfo("StartDateTime", "Provide a valid date for the start time.")); 
        } 
       } 

       if (Errors.Any()) 
        throw new RulesException(Errors); 
      } 
     } 
    } 

Ha senso avere il check-in entrambi i posti nel nostro progetto, ma voglio solo visualizzare un concetto.

1

mi sono imbattuto in questo problema oggi e ho voluto condividere un'altra soluzione ...

[Required(ErrorMessage="Please enter your appointment date?")] 
//[DataType(DataType.Date, ErrorMessage="Appointment date is not a date")] 
[Range(typeof(DateTime), "1/1/1880", "1/1/2200", ErrorMessage = "...")] 
public string AppointmentDate { get; set; } 

Sarà necessario regolare il codice per lavorare con una stringa invece di un datetime (presumibilmente facile se questo fa parte del modello di visualizzazione), ma il messaggio di errore funziona come previsto e la stringa è garantita come data valida (eventualmente con un orario).

Problemi correlati