开发者

ASP.Net MVC3 conditional validation

开发者 https://www.devze.com 2023-03-05 15:05 出处:网络
I\'m having some troubles with validation on my application. Let\'s say I\'ve the following models: public class Company

I'm having some troubles with validation on my application. Let's say I've the following models:

    public class Company
    {
        public int id { get; set; }
        [Required]
        public String Name { get; set; }
        public String Location { get; set; }
        public List<Contacts> Contacts { get; set; }
    }

    public class Contact
    {
        public int id { get; set; }
        [Required]
        public String Name { get; set; }
        [DataType(DataType.EmailAddress)]
        public String Email { get; set; }
        public String Telephone { get; set; }
        public String Mobile { get; set; }
    }

Now in my company create view I've two buttons, one to add contacts to the company, and another one to create the new company. I detected which button was used in my controller like this (both buttons are named "button"):

    [HttpPost]
    public ActionResult Create(String button, FormCollection collection)
    {
        if(button == "AddContact")
        {
            AddContact(collection);
        }
        else
        {
            CreateCompany(collection);
        }
    }

While it's being created the object that represents the company that it's being create is stored in the session (for example HttpContext.Session["company"] = company;)

Now the problem is that if, for example, I try to add a contact without first specifying the company name, i get a validation error because the company name is required, which shouldn't happen because the user might want to add the contacts before adding the company info. Or if I try to save the company, I also get a validation error, because usually when saving the "add contact" form is empty, which means that the contact name (which is required as well) was not specified.

What I want to know is that if it's possible to validate the contact properties only when the addContact button is used, and validate the company properties only when the c开发者_开发技巧reateCompany button is pressed.

For now i only need to do this serve-side, but if anyone has a solution to do this client-side as well i would appreciate the help.


You could trigger your own validation on the individual objects using Validator.TryValidateObject(Object, ValidationContext, ICollection)


You can provide conditional validation using the Entity Framework by overriding DbEntityValidationResult in the DbContext. When this validation occurs in the DbContext you can access other entities. When validating a contact you can check the company too. For example:

    protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
    {
        var result = base.ValidateEntity(entityEntry, items);
        ValidateContact(result);
        return result;
    }

    private void ValidateContact(DbEntityValidationResult result)
    {
        var contact= result.Entry.Entity as Contact;
        if (contact!= null && contact.ContactId != 0)
        { 
            // Add validation code here, such as:
            if(!string.IsNullOrEmpty(contact.Company.Name){ 
                     result.ValidationErrors.Add(
                     new DbValidationError(
                       "Contact",
                       "Company name cannot be null or empty when validating contacts.")
                     );
            }
        }
    }

See Julia Lerman's Programming Entity Framework: DbContext http://www.amazon.com/Programming-Entity-Framework-Julia-Lerman/dp/1449312969 for more details.

0

精彩评论

暂无评论...
验证码 换一张
取 消