I have used Data Annonation in my project to validate my modals. e.g I have a class with following Data Annonation properties
public class tbl_store
{
[Required(ErrorMessage = "Name is required")]
public string Name{ get; set; }
[Required(ErrorMessage = "Email is required")]
[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
public string Email{ get; set; }
[Required(ErrorMessage = "Phone Number is required")]
[DataType(DataType.PhoneNumber, ErrorMessage = "Invalid Phone Number")]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Invalid Phone number")]
public string Contact{ get; set; }
[Required(ErrorMessage = "Address is required")]
public string Address{ get; set; }
[Required(ErrorMessage = "Detail is required")]
public string Detail{ get; set; }
}
Now i have a form that use the above class as Model and have input textboxes for Name , Email and Contact fields.
When i submit this form, i am using following ActionResult method
[HttpPost]
public ActionResult createStore(tbl_store modal)
{
try
{
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
tbl_store objStore = new tbl_store()
{
Name = modal.Name,
Email = modal.Email,
Contact = modal.Contact
};
context.tbl_store.Add(objStore);
}
context.SaveChanges();
}
}
catch (DbEntityValidationException ex)
{
}
// Some more code
}
Here at Context.SaveChanges() exception throws with message System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
When i debug the expcetion, it throws me exception due to Address and Detail fields are required fields and are posted with null values.
I don't wanna add this fields in this form.
How can i nullify Data Annonation for these two fields or some things else to post this form data successfully.
AddressandDetailslater for the same store.