MVC Validation attributes are not working. When i hit the Submit button without entering any data in add view,it supposed to throw an Validation error but it's not throwing validation error. I have added validation attributes to the model and also check ModelState property, but still it's not working
In my config file,have the below settings
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Below is the model I'm refering to the view.
public class Student
{
public int StuID { get; set; }
[DisplayName("Student Name")]
[Required(ErrorMessage = "Name Required!")]
public string StuName { get; set; }
[Required(ErrorMessage = "Please Mention Education!")]
public string Education { get; set; }
[DisplayName("Birth Date")]
public DateTime? BirthDate { get; set; }
[DisplayName("Gender")]
public string Sex { get; set; }
[Required(ErrorMessage = "Please Enter Course Name!")]
public string Course { get; set; }
//public string Location { get; set; }
[DisplayName("Location")]
public int LocID { get; set; }
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Invalid Phone number")]
[Required(ErrorMessage = "Phone Number Required!")]
public String Contact { get; set; }
}
Controller :
public ActionResult Add(Student student)
{
if (ModelState.IsValid)
{
using (SqlConnection SqlCon = new SqlConnection(conn))
{
SqlCon.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Student(StuName,Education,Sex,Course,BirthDate,LocID,Contact) Values(@StuName,@Education,@Sex,@Course,@BirthDate,@LocID,@Contact) ", SqlCon);
cmd.Parameters.AddWithValue("@StuName", student.StuName);
cmd.Parameters.AddWithValue("@Education", student.Education);
cmd.Parameters.AddWithValue("@Sex", student.Sex);
cmd.Parameters.AddWithValue("@Course", student.Course);
cmd.Parameters.AddWithValue("@BirthDate", student.BirthDate.HasValue ? (object)student.BirthDate : DBNull.Value);
cmd.Parameters.AddWithValue("@LocID", student.LocID);
cmd.Parameters.AddWithValue("@Contact", string.IsNullOrEmpty(student.Contact) ? DBNull.Value : (object)student.Contact);
cmd.ExecuteNonQuery();
}
}
return View();
}
I have checked the ModelState property also in controller but still it is not working. Am i missing something here?