我正在尝试对我的日期进行验证,以便开始日期必须为<结束日期。如果结束日期是在开始日期之前,我会抛出异常。如何在我的屏幕上显示此异常,所以当我按下搜索按钮并且日期错误时会显示一条消息?
public ActionResult SearchFree(DateTime? StartDate, DateTime? EndDate)
{
if (StartDate.HasValue && EndDate.HasValue)
{
DateTime d1 = StartDate.Value;
DateTime d2 = EndDate.Value;
TimeSpan span = d2 - d1;
if (span.Days <= 0)
{
throw new ArgumentOutOfRangeException("start date must be before end date");
}
try
{
DBContext.Current.Open();
var model = Reservation.SelectFreeRooms(StartDate, EndDate);
DBContext.Current.Close();
return View(model);
}
catch (ArgumentException ae)
{
throw ae;
}
}
return View(new List<dynamic>());
}
答案 0 :(得分:4)
public ActionResult SearchFree(DateTime? StartDate, DateTime? EndDate)
{
if (!StartDate.HasValue || !EndDate.HasValue)
{
ModelState.AddModelError("Date", "Dates are empty");
return View();
}
if(StartDate.Value > EndDate.HasValue
{
ModelState.AddModelError("Date", "start date must be before end date");
return View();
}
try
{
DBContext.Current.Open();
var model = Reservation.SelectFreeRooms(StartDate, EndDate);
DBContext.Current.Close();
return View(model);
}
catch ()
{
ModelState.AddModelError("", "Db problem");
return View();
}
}
但最好的方法 - 使用某些模型并使用属性验证