
Untitled
By: a guest on
May 10th, 2012 | syntax:
None | size: 1.41 KB | hits: 20 | expires: Never
ASP.NET MVC 3 - Setting null field in DTO when binding to HTTP POST instead of failing
[HttpPost]
public ViewResult Index(ResultQueryForm queryForm)
{
...
}
public class ResultQueryForm
{
public DateTime? TimestampStart { get; set; }
public DateTime? TimestampEnd { get; set; }
public string Name { get; set; }
}
[HttpPost]
public ViewResult Index(DateTime? startDate)
{
// 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
}
if(!Model.IsValid)
{
return View(); // ooops didn't work
}
else
{
return RedirectToAction("Index"); //horray
}
[DateTimeFormat(ErrorMessage = "Invalid date format.")]
public DateTime? TimestampStart { get; set; }
[DateTimeFormat(ErrorMessage = "Invalid date format.")]
public DateTime? TimestampEnd { get; set; }
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DateTimeFormatAttribute : ValidationAttribute
{
public override bool IsValid(object value) {
// allow null values
if (value == null) { return true; }
// when value is not null, try to convert to a DateTime
DateTime asDateTime;
if (DateTime.TryParse(value.ToString(), out asDateTime)) {
return true; // parsed to datetime successfully
}
return false; // value could not be parsed
}
}