加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – Asp.NET MVC – DataAnnotations和ModelState.

发布时间:2020-12-16 03:35:00 所属栏目:asp.Net 来源:网络整理
导读:我正在从 Pro ASP.NET MVC 4这本书中学习ASP.NET MVC(顺便说一句,我喜欢这本书). 我还在开头的章节中,它向我展示了System.ComponentModel.DataAnnotations命名空间属性,如何使用这些注释来填充我的模型类,然后如何使用它们来检查模型是否有效(ModelState.IsV
我正在从 Pro ASP.NET MVC 4这本书中学习ASP.NET MVC(顺便说一句,我喜欢这本书).

我还在开头的章节中,它向我展示了System.ComponentModel.DataAnnotations命名空间属性,如何使用这些注释来填充我的模型类,然后如何使用它们来检查模型是否有效(ModelState.IsValid in the控制器).

例如:

public class GuestResponse
{
    [Required(ErrorMessage = "Please enter your name"]
    public string Name { get; set; }
}

...

public ViewResult RsvpForm(GuestResponse guestResponse)
{
    if(ModelState.IsValid)
    {
        return View("Thanks",guestResponse);

    }

}

有几件事让我感到不安.

>为什么我想要在我的域模型中散布一堆属性?我喜欢我的域模型纯粹而且没有任何特定于实现的东西,并且任何真实世界模型都太复杂而不能像这样使用声明性验证.
>验证属性的ErrorMessage参数是否有些与View相关?这样的东西不属于UI层吗?例如…如果由于空间限制我想要移动版本而不是说“请输入你的名字”说“需要姓名”怎么办?但这是我的模特!
>为什么我要使用ModelState.IsValid来确定模型的状态?模特不应该告诉我吗?我知道ModelState正在使用我的模型中的DataAnnotations属性,但这似乎只适用于非常简单的模型.更复杂的模型甚至可能没有有效/无效状态,它可能只有各种阶段和状态.我在这里散步,但我不喜欢以声明的方式说出是什么让我的模型有效或无效.

任何建议,保证或验证这些想法将不胜感激.

解决方法

以下是我对你问题的回答:

1) Why do I want a bunch of attributes littered throughout my domain model? I like my domain model pure and free from any stuff that is
implementation specific,and any real world model would be too complex
to just use declarative validation like this.

你绝对不希望这样.您想要的是拥有专为视图目的而设计的视图模型.这个视图模型将包含数据注释,而不是您的域模型.然后,控制器将在域模型和视图模型之间进行映射,并将视图模型传递给视图.将视图模型视为一个或多个域模型的投影.为了简化您的域和视图模型之间的映射,您可以签出AutoMapper.基本的经验法则是视图不应该知道您的域模型.

2) Aren’t the ErrorMessage parameters of the validation attributes somewhat View related? Doesn’t something like that belong in the UI
layer? For example…what if due to space constraints I want the
mobile version to instead of saying “Please enter your name” say “Name
required”? But here it is in my model!

完全同意你的看法.这就是为什么你应该有一个专门为视图目的而设计的视图模型类的原因.

3) Why do I want to use ModelState.IsValid to determine the status of the
model? Shouldn’t the model tell me? I understand that ModelState is
making use of the DataAnnotations attributes that are in my model,but
this seems like it would only work for very simple models. A more
complex model might not even have a valid/invalid state,it might just
have various stages and states. I’m sort of rambling here,but I don’t
like the idea of declaratively saying what makes my model valid or
invalid.

我再次同意你的看法.声明性验证(例如你开箱即用的数据注释)对于Hello World类型的应用程序非常有用,但是一旦你开始用复杂的验证规则编写真实世界的应用程序,你很快就会意识到声明式方法根本不会削减芥末.正是出于这个原因,我使用了FluentValidation.NET.它为您提供了一个非常漂亮和流畅的语法来表达任意复杂的验证规则,integrates easily with ASP.NET MVC并允许unit test your validation rules完全隔离.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读