Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In asp.net mvc the people validate model this below way

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 could do the model validation same way in any C# win and webform application?

like image 319
Mou Avatar asked Mar 29 '15 08:03

Mou


2 Answers

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.       
}
like image 177
Praveen Paulose Avatar answered Oct 17 '22 18:10

Praveen Paulose


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

like image 28
JustLearning Avatar answered Oct 17 '22 19:10

JustLearning