首先使用实体​​框架模型进行MVC3条件验证

时间:2015-01-20 16:37:24

标签: asp.net-mvc entity-framework

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

这是我到目前为止的代码:

查看:          

@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();
    }

我的自定义类文件:

[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" });
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

不是好友类,但是类本身应该实现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" });
        }
    }
}