ASP.NET MVC 3 validation error not firing when a complex type is used in Entity Framework

发布于 2022-09-05 15:42:13 字数 1339 浏览 26 评论 0

Right now I'm working on a form to let user to post content, I want to make use of the WMD editor, so in my Entity Framework model I have a complex type named Content, it holds HTML and WMD fields.

In the form, there's a textbox for the title, and a WMD editor for Content, I used the FluentValidation framework, as follow:

public class ArticleValidator : AbstractValidator<Article>
{
    public ArticleValidator()
    {
        RuleFor(x => x.Title).NotEmpty();
        RuleFor(x => x.Content.WMD).NotEmpty();
    }
}

When I submit this form without entering anything, the client-side validation only catches the Title as invalid. If I enter something in the Title, the form submits (even though the content is empty), then the error is caught on the server-side (empty content), the page is then reloaded with the information I entered, but no error message was displayed.

It seems the complex type I created in the Entity Framework model is causing this problem. I used to have separate properties for ContentHtml and ContentWMD and it worked fine.

Is there a workaround to this without having to revert back to where I was?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

儭儭莪哋寶赑 2022-09-12 15:42:13

You cannot use nested rule definition like this:

RuleFor(x => x.Content.WMD).NotEmpty();

You need to have another validator for the Content type:

public class ArticleValidator : AbstractValidator<Content>
{
    public ArticleValidator()
    {
        RuleFor(x => x.WMD).NotEmpty();
    }
}

This being said you should not use EF models inside your views. You should use View Models and define validation rules on your view model:

public class ArticleValidator : AbstractValidator<ArticleViewModel>
{
    public ArticleValidator()
    {
        RuleFor(x => x.Title).NotEmpty();
        RuleFor(x => x.Content).NotEmpty();        
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文