Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check modelstate without modelbinding?

I'm getting my feet wet with the Entity Framework and am wondering if there is a way for me to check model state without model binding happening.

Say I create a user primarily from code, is there a way for me to check to make sure it is valid according to my predefined data annotations before I update?

    public ActionResult Index()
    {
        User u = new User();
        u.Username = "test";
        u.Password = "test";
        u.Email = "test";

        DefaultContext db = new DefaultContext();            

        if (ModelState.IsValid)
        {
            db.Users.Add(u);
            db.SaveChanges();
            Response.Write(u.Id);
        }
        else
            // model is not valid

        return View();
    }

The above code does not work because there is no binding happening. Or maybe I am confused of the process.

Thanks.

like image 869
Dietpixel Avatar asked Aug 18 '11 02:08

Dietpixel


2 Answers

ModelState won't be available because it's set up by the model binder. The ModelBinder didn't bind a model so it didn't run validation thus ModelState will be empty.

But that doesn't stop you from using attributes and performing validation.

Assuming you are using the DataAnnotation attributes, you can run the validation without model binding.

Given this class:

public class Widget
{
    public int Id { get; set; }

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

    public decimal Price { get; set; }
}

You can do this:

        var widget = new Widget
                        {
                            Id = 12,
                            Price = 15.57M
                        };

        var context = new ValidationContext(widget, null, null);
        var results = new List<ValidationResult>();
        if( Validator.TryValidateObject( widget, context, results, true ) )
        {
            //Validation Successful
        }
        else
        {
            //Validation Failed
        }

The Name property was not set and the TryValidateObject() will fail. The results collection will have the actual error that occurred.

like image 165
Nathan Ratcliff Avatar answered Sep 22 '22 11:09

Nathan Ratcliff


you can use TryValidateModel or ValidateModel

 User u = new User();
    u.Username = "test";
    u.Password = "test";
    u.Email = "test";


    if (TryValidateModel(u))
     {

     }else{

     }
like image 25
Jayantha Lal Sirisena Avatar answered Sep 22 '22 11:09

Jayantha Lal Sirisena