我写了一个自定义属性:
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);
}
但等到用户提交为时已晚。我想在处理之前检查订单是否存在。我需要向用户显示是否存在的可视指示器。我怎样才能实现这种行为?