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

asp.net-mvc-3 – ASP.Net MVC 3 ModelState.IsValid

发布时间:2020-12-16 03:34:12 所属栏目:asp.Net 来源:网络整理
导读:我刚刚开始使用ASP.Net MVC 3并且在这一点上感到困惑. 在某些示例中,当运行包含输入的控制器中的操作时,将进行检查以确保ModelState.IsValid为true.某些示例未显示正在进行此检查.我应该什么时候进行检查?每当向动作方法提供输入时,是否必须使用它? 解决方
我刚刚开始使用ASP.Net MVC 3并且在这一点上感到困惑.

在某些示例中,当运行包含输入的控制器中的操作时,将进行检查以确保ModelState.IsValid为true.某些示例未显示正在进行此检查.我应该什么时候进行检查?每当向动作方法提供输入时,是否必须使用它?

解决方法

Must it be used whenever an input is provided to the action method?

正是在使用作为操作参数提供的视图模型时,此视图模型具有与之关联的一些验证(例如数据注释).这是通常的模式:

public class MyViewModel
{
    [Required]
    public string Name { get; set; }
}

然后:

[HttpPost]
public ActionResult Foo(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        // the model is not valid => we redisplay the view and show the
        // corresponding error messages so that the user can fix them:
        return View(model);
    }

    // At this stage we know that the model passed validation 
    // => we may process it and redirect
    // TODO: map the view model back to a domain model and pass this domain model
    // to the service layer for processing

    return RedirectToAction("Success");
}

(编辑:李大同)

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

    推荐文章
      热点阅读