0

我已经设置了一些用于实体框架的 POCO 模型类。我在我DbContextValidateEntity覆盖中做了一些验证。DbEntityValidationResult我从函数返回 a ValidateEntity,我可以看到在运行时我确实添加了一些DbValidationErrors。我什至可以ModelState在我的Controller函数内部看到这些错误,使用下面的代码......

catch (DbEntityValidationException ex)
{
    foreach (var entity in ex.EntityValidationErrors)
    {
        foreach (var error in entity.ValidationErrors)
        {
            ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
        }
    }
}

但由于某种原因,这些错误不会在 Razor 视图中显示为所需的属性名称。我使用如下所示的视图模型...

public class CharacterCreateModel
{
    private Character m_character;

    #region Properties

    public Character Character
    {
        get
        {
            return m_character;
        }

        set
        {
            m_character = value;
        }
    }

    #endregion
}

在我的 Razor 视图中,使用这种CharacterCreateModel视图模式进行强类型化,我只使用标准@Html.TextBoxFor等。

验证错误来自Character模型的验证错误正确显示,但来自ValidateEntity函数的验证错误未针对该属性名称显示。

知道为什么不?

4

1 回答 1

1

You need to include the ValidationMessageFor helper in your code to show model level properties.

You should have

@Html.EditorFor(model => model.Character)
@Html.ValidationMessageFor(model => model.Character)

If this in not showing the errors change the

@Html.ValidationSummary(true)

at the top of your view to

@Html.ValidationSummary(false)

so you can see all the validation errors and make sure they're actually being added correctly.

于 2013-10-09T04:54:38.820 回答