How to simulate ModelState.IsValid in winform application for C # for any model check

In asp.net mvc, people test the model as follows

using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models {
    public class Movie {
        public int ID { get; set; }

        [Required]
        public string Title { get; set; }

        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }

        [Required]
        public string Genre { get; set; }

        [Range(1, 100)]
        [DataType(DataType.Currency)]
        public decimal Price { get; set; }

        [StringLength(5)]
        public string Rating { get; set; }
    }

    public class MovieDBContext : DbContext {
        public DbSet<Movie> Movies { get; set; }
    }
}

if (ModelState.IsValid)
    {
        db.Movies.Add(movie);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

How can model validation be done in the same way in any C # win and webform application?

+4
source share
2 answers

You can use the ValidationContext available in DataAnnotes to perform this check. You can make your own class to achieve this in a single line of code, available in 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.       
}
+3
source

Based on Parveen's answer, I created a helper static class that can be reused:

    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;
        }
    }
}

Form.cs ( "" ) :

        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
        };
    }

, asp mvc now

+1

All Articles