什么是 ModelState.IsValid 在 NerdDinner 的 ASP.NET MVC 中有效? [英] What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

查看:28
本文介绍了什么是 ModelState.IsValid 在 NerdDinner 的 ASP.NET MVC 中有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NerdDinner 示例中 Professional ASP.NET MVC 1.0 有一种方法可以创建一个新的晚餐,如下复制(免费 NerdDinner 版本的第 89 页).

On the NerdDinner example of Professional ASP.NET MVC 1.0 there's a method to create a new dinner as copied bellow (page 89 of the free NerdDinner version).

在那里检查 ModelState.IsValid 是否为真.它似乎检查模型是否对数据库有效(即,它捕获数据类型转换,例如格式无效的日期,但不捕获业务规则).是真的吗?

There it checks ModelState.IsValid for true. It seems to check if the model is valid for the database (that is, it catches data type conversions, like dates with invalid format, but not business rules). Is that true?

提交表单时,如果您在日期中有错误,ModelState.IsValid 将为 false,您将返回错误,但仅限于日期,因为 AddRuleViolations 从未执行过.如果您完全取消对 ModelState.IsValid 的检查,那么您将获得所有错误(由于异常),包括无效日期中的标记.那么,为什么要检查 ModelState.IsValid 呢?我错过了什么吗?

When submitting the form, if you have an error in the date, ModelState.IsValid will be false and you'll get back an error, but only for the date because AddRuleViolations was never executed. If you remove the check for ModelState.IsValid completely, then you'll get all the errors (due to the exception), including a marking in the date when it is invalid. Then, why is the check for ModelState.IsValid there at all? Am I missing something?

// 
// POST: /Dinners/Create 

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Create(Dinner dinner) {
    if (ModelState.IsValid) {
        try {
            dinner.HostedBy = "SomeUser"; 

            dinnerRepository.Add(dinner);
            dinnerRepository.Save();

            return RedirectToAction("Details", new {id = dinner.DinnerID }); 
        } catch {
            ModelState.AddRuleViolations(dinner.GetRuleViolations());
        } 
    } 
    return View(dinner); 
} 

推荐答案

ModelState.IsValid 告诉您是否已将任何模型错误添加到 ModelState.

ModelState.IsValid tells you if any model errors have been added to ModelState.

默认模型绑定器会为基本类型转换问题添加一些错误(例如,为int"类型传递非数字).您可以根据您使用的任何验证系统更全面地填充 ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

示例 DataAnnotations 模型绑定器将使用来自模型的 DataAnnotations 属性的验证错误填充模型状态.

The sample DataAnnotations model binder will fill model state with validation errors taken from the DataAnnotations attributes on your model.

这篇关于什么是 ModelState.IsValid 在 NerdDinner 的 ASP.NET MVC 中有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆