【问题标题】:Validation not working on plain objects in ASP.NET MVC验证不适用于 ASP.NET MVC 中的普通对象
【发布时间】:2009-07-25 12:54:53
【问题描述】:

当我将“模型”对象(由 LinqToSQL 生成)发布到控制器时,我可以查询“ModelState.IsValid”,并且如果任何属性上有验证属性并且值未验证,它将被设置为“假”。

但是,如果我发布自己的类的自定义对象,ModelState.IsValid 似乎总是返回“true”,即使该类的属性具有验证属性并且被赋予了不正确的值。

为什么这只适用于 DataContext 模型对象?是什么让这些对象能够与 ModelState.IsValid 一起工作,而普通类却不能?

我怎样才能使它与普通类一起工作?


控制器代码:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogIn(MyProject.Website.ViewModels.Shared.LogIn model)
{
    if (ModelState.IsValid)
        return View(model);

    // ... code to log in the user
}

ViewModel 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using MyProject.Website.Validators;
using System.ComponentModel;

public class LogIn
{

    public LogInModes LogInMode { get; set; }

    [Required] 
    [EmailAddress]
    public string EmailAddress { get; set; }

    public string Password { get; set; }

    public bool RememberMe { get; set; }

    public string ReturnUrl { get; set; }

}

【问题讨论】:

  • 我怀疑不是框架的问题,但是没有一点代码就很难判断问题出在哪里。

标签: asp.net-mvc validation viewmodel


【解决方案1】:

您是否将DataAnnotationsModelBinder 设置为您在Global.asax 文件的Application_Start 事件中的默认模型绑定器?

protected void Application_Start() {
    ModelBinders.Binders.DefaultBinder = new DataAnnotationsModelBinder();
}

因为据我所知,System.ComponentModel.DataAnnotations namescape 下的属性仅适用于该模型绑定器。

您也可以仅为该操作设置模型绑定器:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogIn( [ModelBinder(typeof(DataAnnotationsModelBinder))]
    Yieldbroker.Website.ViewModels.Shared.LogIn model) {
    //...
}

this blog post 和这个question

【讨论】:

    【解决方案2】:

    你不应该试试 if (model.IsValid()) 吗??

    编辑:抱歉,这需要从 Model 类继承的 Login 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      • 2023-03-19
      相关资源
      最近更新 更多