具有数据注释的类级自定义验证ASP MVC

时间:2016-08-19 10:47:54

标签: asp.net-mvc data-annotations custom-attributes

我有以下属性

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class EnsureDeliveryRegistered: ValidationAttribute
{
    public EnsureDeliveryRegistered() { }

    public override bool IsValid(object value)
    {
        return value != null &&
        value is DeliveryViewModel &&
        IntranetOnlineForms.Util.Util.GetDeliveryCount((DeliveryViewModel)value) > 0;
    }
}

适用于以下课程

[EnsureDeliveryRegistered(ErrorMessage = "Defined delivery date(s) result in 0 deliveries to register. Make sure you have the right date; if delivery is a recurring one make sure selected dates and days of week / period will match at least one delivery.")]
    public class DeliveryViewModel
{ //class here }

我的页面视图模型中有这种类型的属性

public class RegisterDeliveryPage
{
    public RegisterDeliveryPage()
    {
        Delivery = new DeliveryViewModel();         
    }

    [Required]
    public DeliveryViewModel Delivery { get; set; }

    //the rest of the code
}

当我提交页面时,会发布整个RegisterDeliveryPage模型

[Route("register")]
    [HttpPost]
    public ActionResult RegisterNewDelivery(RegisterDeliveryPage model)
    {
        try
        {
            if (ModelState.IsValid)
            {
                //todo
            }

            return View("Register", model);
        }
        catch (Exception exc)
        {

        }
    }

在我检查ModelState之后,我可以看到有一个带有注释属性中指定的错误消息的“Delivery”键,但是当我想在视图中显示它时,它没有显示出来。

@Html.ValidationMessage("Delivery")

我在另一个属性中有相同的设置,并且真的不知道这里出了什么问题。

0 个答案:

没有答案