我写了一个自定义属性:
public class VerifyOrderAttribute : RequiredAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (DoesOrderExist((string)value))
return ValidationResult.Success;
ValidationResult vr = new ValidationResult("Order does not exist");
return vr;
//return base.IsValid(value, validationContext);
}
private bool DoesOrderExist(string sOrderSequence)
{
PullParts.PartProcessor o = new PullParts.PartProcessor();
bool result = o.CheckOrder(sOrderSequence);
return result;
}
}
我将 VerifyOrder 属性与我的属性一起使用:
[Required(ErrorMessage= "Order number is required")]
[RegularExpression(@"\d{2}-\d{6}-\d{2}", ErrorMessage="Order number must be in format XX-XXXXXX-XX")]
[VerifyOrder(ErrorMessage="Order number does not exist")]
public global::System.String OrderNumber
{
get
{
return _OrderNumber;
}
set
{
_OrderNumber = value;
}
}
private global::System.String _OrderNumber;
在我看来,我调用了 ValidationMessageFor():
<div>
<label class="span2">*Order Number:</label>
@Html.TextBoxFor(x => x.Request.OrderNumber, new { @class = "span3" })
@Html.ValidationMessageFor(x => x.Request.OrderNumber)
</div>
看起来 ValidationMessageFor 没有为我的自定义属性调用 IsValid() 。我希望我的自定义属性 VerifyOrder 像Required 属性一样工作。我需要做什么?
提前致谢!
编辑(从评论中移出)
我确实像这样在控制器中检查了它:
[HttpPost]
public ActionResult Index(MSDModel m) {
if (ModelState.IsValid) {
model.Request = m.Request;
model.SaveRequest();
model.Request.OrderNumber = string.Empty;
}
return View(model);
}
但等到用户提交为时已晚。我想在处理之前检查订单是否存在。而且我需要向用户显示它是否存在的视觉指示器。我怎样才能实现这种行为?