检查日期选择器值是否小于今天的日期MVC

时间:2014-05-01 22:58:03

标签: c# asp.net asp.net-mvc-4

我正在MVC4中构建应用程序,我正在努力确保当用户从日期选择器输入日期并提交表单时,输入的日期不小于今天的日期。

这是我的模特:

 public class Job
{

    [Required]
    [DisplayName("Target Date for Site Survey")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? TargetDateSurvey { get; set; }

}

我的控制器:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Job job)
    {
        if (ModelState.IsValid)
        {
            job.CreatedDate = DateTime.Now;
            job.JobstatusID = 1;
            db.Jobs.Add(job);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.ClientID = new SelectList(db.Clients, "ClientID", "ClientName", job.ClientID);
        ViewBag.JobstatusID = new SelectList(db.JobStatusLookUps, "JobstatusID", "JobStatusDescription", job.JobstatusID);
        ViewBag.JobID = new SelectList(db.AssignAssessors, "JobID", "JobID", job.JobID);
        return View(job);
    }

观看:

@model fieldManagementSystem.Models.Job

                <div class="editor">
                    @Html.LabelFor(model => model.TargetDateSurvey)
                    @Html.EditorFor(model => model.TargetDateSurvey)
                    @Html.ValidationMessageFor(model => model.TargetDateSurvey)
                </div>

我会在模型或控制器中对此进行验证吗?这样做的最佳方法是什么?

任何指导都将不胜感激

1 个答案:

答案 0 :(得分:1)

在控制器中验证它非常简单。您添加自定义无效状态,然后ModelState将相应地执行操作。

public ActionResult Create(Job job)
{
    if (job.TargetDateSurvey.Value < DateTime.Today)
    {
        ModelState.AddModelError("TargetDateSurvey", "Date must be today or later.");
    }

    if (ModelState.IsValid)
    ...
}