Entity Framework 模型优先的 MVC3 条件验证

MVC3 Conditional Validation with Entity Framework Model First

我想在我的应用程序中使用条件验证,但我似乎无法弄清楚。数据注释验证工作正常,如果我将字段留空,will return 到带有此类指示的表单,但有条件的没有任何反应。我非常希望能够将额外的代码保留在控制器、视图和 EF 生成的文件之外(这就是我使用密封 class 的原因)。 ("ConditionIsMet" 显然是 return 的布尔值,只是作为一个例子)。我错过了什么?

这是我目前的代码:

查看:

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>TestApplications</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.FullName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FullName)
        @Html.ValidationMessageFor(model => model.FullName)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>'

控制器:

    [HttpPost]
    public ActionResult TestApplication(TestApplications application)
    {
        if (ModelState.IsValid)
        {
            DB_connection.TestApplications.Add(application);
            DB_connection.SaveChanges();
            return RedirectToAction("Index");
        }
        return View();
    }

我的自定义 class 文件:

[MetadataType(typeof(TestApplicationsMetadata))]
public partial class TestApplications
{
    internal sealed class TestApplicationsMetadata : IValidatableObject
    {

        [Required(ErrorMessage = "Name is required.")]
        public string FullName { get; set; }


        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (!conditionIsMet)
            {
                yield return new ValidationResult
                 ("Condition was not met", new[] { "FullName" });
            }
        }
    }
}

不是好友 class,而是 class 本身应该实现 IValidatableObject:

[MetadataType(typeof(TestApplicationsMetadata))]
public partial class TestApplications : IValidatableObject
{
    internal sealed class TestApplicationsMetadata
    {
        [Required(ErrorMessage = "Name is required.")]
        public string FullName { get; set; }
    }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (!conditionIsMet)
        {
            yield return new ValidationResult
             ("Condition was not met", new[] { "FullName" });
        }
    }
}