How can I make an ASP.NET MVC DateTime picker form field display a message if datetime is taken?

Viewed 129

I have a form that works with entity framework. This is my model:

    public class CarModel
    {
        public int id { get; set; }
        [Required]
        [DisplayName  ("Make")]
        public string Maker { get; set; }
        [Required]
        public string Model { get; set; }
        [Required]
        public string Year { get; set; }
        [Required]
        public string Engine{ get; set; }
        [Required]
        public string VIN { get; set; }
        [DisplayName("Date and Time")]
        public DateTime Date { get; set; }
        public string Work { get; set; }
   }     

And this is the view:

   <div class="form-group">
            @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" , type = "datetime-local" } })
                <label>Please keep in mind our working hours are <br>9:00-17:00 Monday to Friday</label>
                @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
            </div>
   </div>

So as you can see, I have a DateTime field in the form. When someone inserts date and time that is already "taken", I want the program to display a view with the following text: "we're sorry but the date and time are already taken". What is the shortest way I can do that?

2 Answers

a Simple way for get this work in Your Controller

    public ActionResult ActionResult(CarModel vm)
    {
        if (ModelState.IsValid)
        {
            if (_dbcontext.Car.Any(x => x.Date == vm.Date))
            {
                ModelState.AddModelError("Date ", "we're sorry but the date and time are already taken");
                return View(vm);
            }
            // other works such as Save Data
        }

        return View(vm);
    }

I don't think we can use '@Html.Validation' for this. Instead, You can create an another div with the error message you want to throw and display it if the date/time is not available.

Related