Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 10th, 2012  |  syntax: None  |  size: 1.41 KB  |  hits: 20  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. ASP.NET MVC 3 - Setting null field in DTO when binding to HTTP POST instead of failing
  2. [HttpPost]
  3. public ViewResult Index(ResultQueryForm queryForm)
  4. {
  5.    ...
  6. }
  7.  
  8. public class ResultQueryForm
  9. {
  10.    public DateTime? TimestampStart { get; set; }
  11.    public DateTime? TimestampEnd { get; set; }
  12.    public string Name { get; set; }
  13. }
  14.        
  15. [HttpPost]
  16. public ViewResult Index(DateTime? startDate)
  17. {
  18.    // If the user enters an invalid date, the controller action won't even be run because   the MVC model binding will fail and return an error message to the user
  19. }
  20.        
  21. if(!Model.IsValid)
  22. {
  23.   return View(); // ooops didn't work
  24. }
  25. else
  26. {
  27.   return RedirectToAction("Index"); //horray
  28. }
  29.        
  30. [DateTimeFormat(ErrorMessage = "Invalid date format.")]
  31. public DateTime? TimestampStart { get; set; }
  32. [DateTimeFormat(ErrorMessage = "Invalid date format.")]
  33. public DateTime? TimestampEnd { get; set; }
  34.  
  35.  
  36. [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
  37. public class DateTimeFormatAttribute : ValidationAttribute
  38. {
  39.     public override bool IsValid(object value) {
  40.  
  41.         // allow null values
  42.         if (value == null) { return true; }
  43.  
  44.         // when value is not null, try to convert to a DateTime
  45.         DateTime asDateTime;
  46.         if (DateTime.TryParse(value.ToString(), out asDateTime)) {
  47.             return true; // parsed to datetime successfully
  48.         }
  49.         return false; // value could not be parsed
  50.     }
  51. }