dropdownlist为所选值所需的mvc

时间:2014-01-13 01:52:42

标签: asp.net-mvc

MVC 4我可以选择在列表1中放置两个电子邮件地址是强制性的 和下拉列表首选电子邮件工作/替代 在提交时我想验证下拉列表的选定值以及所选值,以使工作电子邮件地址或备用电子邮件地址字段成为必需 我怎么做 ?是否可以通过自定义验证来实现?

型号:

    public string WorkEmail { get; set; }
    public string AlternativeEmail { get; set; }
    public List<SelectListItem> PreferredEmails { get; set; }

2 个答案:

答案 0 :(得分:1)

这是解决方案

 public class WorkModel
    {
        [CorrectMail]
        public string WorkEmail { get; set; }
        [CorrectMail]
        public string AlternativeEmail { get; set; }
        public string PreferredEmail { get; set; }
    }

    public class CorrectMail : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var model = validationContext.ObjectInstance as WorkModel;
            if (model == null) return new ValidationResult("Model is empty");

            if (model.PreferredEmail == "WorkEmail" && string.IsNullOrEmpty(model.WorkEmail))
            {
                return new ValidationResult("You have selected work email but did not fill it");
            }
            if (model.PreferredEmail == "AlternativeEmail" && string.IsNullOrEmpty(model.AlternativeEmail))
            {
                return new ValidationResult("You have selected alternative email but did not fill it");
            }
            return ValidationResult.Success;
        }
    }

答案 1 :(得分:0)

是的,可以执行自定义验证例程。我首选的方法是Validating in the Service Layer