제 질문은 MVC 2 사용자 지정 유효성 검사에 관한 것입니다. 나는 특정 문제에 붙어있어, 나는 그 문제를 해결하는 방법을 모르고있다. 나는 그것을 논리적으로하고 나서 코드로 구현하는 방법을 더 알아 내고 있다고 확신한다.Asp.Net MVC 2 사용자 지정 유효성 검사 문제
그래서 제품에 대한 메타 데이터 클래스가 있습니다. 각 제품에는 PK 인 제품 ID가 있으며 분명 고유합니다. 각 제품에는 고유 한 제품 코드도 있습니다. 고객은 제품 코드를 입력하지만 코드의 특성상 하나의 코드 만 하나의 제품에 연결되므로 고유 할 수 있습니다. 여기
메타 데이터 클래스의 코드 조각입니다 : 새로운 제품을 만들 때public partial class ProductMetadata
{
[DisplayName("Product Name")]
[Required(ErrorMessage = "Product Name is required.")]
public string ProductName { get; set; }
[DisplayName("Product Code")]
[Required(ErrorMessage = "Product Code is required.")]
[ProductCodeAlreadyExistsValidator(ErrorMessage = "This Product code is in use.")]
public string ProductCode { get; set; }
}
'ProductCodeAlreadyExistsValidator은'완벽하게 작동합니다. 문제는이 속성에 대해 유효성 검사를 다시 수행하면서 기존 제품을 편집하는 것입니다. 데이터베이스에서 자체를 찾습니다. 결과가 유효하지 않습니다. 그러나 나는 그것으로 벽돌 벽에 부딪 힐 것으로 보인다
이public class ProductCodeAlreadyExistsValidator : ValidationAttribute
{
private readonly object typeId = new object();
private const string defaultErrorMessage = "Product Code {0} is already present in the system.";
public ProductCodeAlreadyExistsValidator()
: base(defaultErrorMessage)
{
}
public override object TypeId
{
get
{
return typeId;
}
}
public string CustomerType { get; set; }
public string CustomerFriendlyType { get; set; }
public override string FormatErrorMessage(string roleName)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, roleName);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!IsValid(value))
{
string errorMessage = string.Format(defaultErrorMessage, validationContext.MemberName, value as string);
return new ValidationResult(errorMessage, new string[] { validationContext.MemberName });
}
return null;
}
public override bool IsValid(object value)
{
bool alreadyPresent = false;
string ProductCode = value as string;
using (ModelContainer ctn = new ModelContainer())
{
alreadyPresent = ctn.Products.Where(t => t.ProductCode == ProductCode).Count() > 0;
}
return !alreadyPresent;
}
}
그것은 비교적 간단한 수정 될 수 있습니다 여기에
는 사용자 정의 유효성 검사기에서 조각입니다. 누구든지 조언을 해줄 수 있습니까?