How to simulate ModelState.IsValid in C# winform application for any model validation
You can use the ValidationContext available in the DataAnnotations to perform this validation. You may want to make your own class to achieve this in a single line of code as available in the web applications.
var validationContext = new ValidationContext(movie, null, null);
var results = new List<ValidationResult>();
if (Validator.TryValidateObject(movie, validationContext, results, true))
{
db.Movies.Add(movie);
db.SaveChanges();
//Instead of a Redirect here, you need to do something WinForms to display the main form or something like a Dialog Close.
//return RedirectToAction("Index");
} else {
//Display validation errors
//These are available in your results.
}
Based on Parveen's answer i created a helper static class, which can be re-used:
public static class ModelState
{
public static List<string> ErrorMessages = new List<string>();
public static bool IsValid<T>(T model) {
var validationContext = new ValidationContext(model, null, null);
var results = new List<ValidationResult>();
if (Validator.TryValidateObject(model, validationContext, results, true))
{
return true;
}
else {
ErrorMessages = results.Select(x => x.ErrorMessage).ToList();
return false;
}
}
}
and in your Form.cs
("Controller") you can call it like this:
private void btnSave_Click(object sender, EventArgs e)
{
var customerResource = GetViewModel();
if (ModelState.IsValid<CustomerResource>(customerResource)) {
}
}
private CustomerResource GetViewModel() {
return new CustomerResource() {
CustomerName = txtName.Text,
Phone = txtPhone.Text
};
}
So this more or less works like asp mvc now