我创建了一个名为Subject
的类,该类具有Department
作为外键。 ShortNameValidation
是ValidationAttribute
,它验证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;
}
}
}
答案 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
}