在C#MVC中的表单验证中使用外键对象

时间:2019-04-17 18:54:36

标签: c# asp.net-mvc entity-framework

我创建了一个名为Subject的类,该类具有Department作为外键。 ShortNameValidationValidationAttribute,它验证ShortName的格式(ShortName的第三个字符必须等于Department的{​​{1 }}属性)。验证在控制器内部使用,该控制器通过键入名称,简称和从预定义的部门下拉列表中选择部门来创建新主题。

我尝试直接在SingleKey方法内部访问subject.Department,但这是IsValid。目前,我唯一的解决方案是使用null从数据库中手动读取部门。

是否有更优雅的解决方案来自动注入DepartmentId

代码:

subject.Department

查看:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Example.Models
{
    public class Subject
    {
        public int Id { get; set; }

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

        [Required]
        [MinLength(4)]
        [MaxLength(15)]
        [ShortNameValidation]
        public string ShortName { get; set; }

        [ForeignKey("Department")]
        public int DepartmentId { get; set; }

        public virtual Department Department { get; set; }
    }

    internal class ShortNameValidationAttribute : ValidationAttribute
    {
        private AppContext _appContext = new AppContext();

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            Subject subject = validationContext.ObjectInstance as Subject;
            // subject.Department returns null - fetch the department from the database
            Department department = _appContext.Departments.Find(subject.DepartmentId);

            if (subject.ShortName[2] != department.SingleKey[0])
            {
                return new ValidationResult("Invalid short name");
            }

            return ValidationResult.Success;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

确保您在GET上填充Department

[HttpGet]
public ActionResult Create()
{
 // example only
 Subject subject = new Subject 
 {
     Id = 1,
     DepartmentId = 1,
     Name = 1,
     Department = new Department() { SingleKey = "Science" }, 
     ShortName = "Science"
 };
 return View(subject);
}

然后在您的表单中确保您拥有Department

的隐藏属性。
 @Html.HiddenFor(m => m.Department.SingleKey) // now this will model bind nicely

现在,将表单发布到ShortNameValidationAttribute中后,您将填充Department

Subject subject = validationContext.ObjectInstance as Subject;
if(subject.Department != null)
{
   // do validation
}

enter image description here