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.
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.
you can use TryValidateModel
or ValidateModel
User u = new User();
u.Username = "test";
u.Password = "test";
u.Email = "test";
if (TryValidateModel(u))
{
}else{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With