-1

I'm using MVC 5 and I want to make validation to check if DateOfEvent existing in database and I'm using remote validation but it's not working. I want to see like this output enter image description here

I'm using sql server and this is my database enter image description here

Model

public partial class tblEvent
{
    public int EventId { get; set; }
    public string Descripstions { get; set; }

    [Display(Name = "DateOfEvent")]
    [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy hh:mm tt}", ApplyFormatInEditMode = true)]
    //Using Remote validation attribute   
    [Remote("IsDateOfEventAlreadySigned", "Event", HttpMethod = "POST", ErrorMessage = "Date Of Event already exists in database.")]
    public DateTime? DateOfEvent { get; set; }

    [Display(Name = "EmpName")]
    [Remote("IsEmpNameAlreadySigned", "Event", HttpMethod = "POST", ErrorMessage = "EmpName already exists in database.")]
    public string EmpName { get; set; }
}

Controller

public class EventController : Controller
{
    [HttpPost]
    public JsonResult IsDateOfEventAlreadySigned(DateTime? DateOfEvent)
    {
        return Json(db.tblEvents.Any(u => u.DateOfEvent == DateOfEvent), JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public JsonResult IsEmpNameAlreadySigned(string EmpName)
    {
        return Json(!db.tblEvents.Any(u => u.EmpName == EmpName), JsonRequestBehavior.AllowGet);
    }

    private MyDatabaseEntities db = new MyDatabaseEntities();
  • To help us better answer your question, please provide the [mcve] – prinkpan Jan 06 '20 at 10:53
  • Hi there. As it stands, your question is lacking a **lot** of detail. To start with: what database are you using (e.g. MS SQL Server)? What library are you using for data access (e.g Entity Framework). Finally, what have you tried? The code doesn't need to compile, but people here typically look for effort first – Brendan Green Jan 06 '20 at 10:53
  • When the form is posted back you need to run a SQL query to check if this date exists in any of the rows in the column of the table where you store it (by comparing that value to existing values and seeing how many matching results you get). Beyond that, we can't tell you anything more specific because you haven't given us any context about your program. – ADyson Jan 06 '20 at 11:33
  • Did you try [this](https://stackoverflow.com/questions/24863634/mvc-5-remote-validation) one ? – Nguyễn Văn Phong Jan 06 '20 at 12:01
  • I try remote validation but it's not working – Jhon Lester Jan 07 '20 at 07:08

1 Answers1

0

Just include js to your .cshtml I hope this will fix your issue

<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script src="~/Scripts/jquery.validate.min.js"></script>  
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  

and for more details refer this URL

https://www.c-sharpcorner.com/blogs/remote-validation-in-mvc-5-using-remote-attribute

Ishwar Gagare
  • 723
  • 3
  • 9