1

我正在我的网络应用程序中实施验证......问题似乎是过度验证?!

控制器代码如下所示:

[HttpPost]
[Authentication]
public ActionResult Create([Bind(Exclude = "Id")] CaseInfo caseInfo)
{
    if (!ModelState.IsValid)
    {
        SetupViewData();
        return View();
    }

    _repository.Create(caseInfo);
    return RedirectToAction("List");
}

这是 CaseInfo 实现:

public class CaseInfo :IValidatableObject
{   
    public virtual Guid Id { get; set; }
    public virtual DateTime ReferralDate { get; set; }
    public virtual int Decision { get; set; }
    public virtual string Reason { get; set; }
    public virtual DateTime StartDate { get; set; }
    public virtual DateTime EndDate { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        throw new NotImplementedException();
    }
}

还有我的 CaseInfoMap:

public sealed class CaseInfoMap : ClassMap<CaseInfo>
{
    public CaseInfoMap()
    {
        Id(x => x.Id).Not.Nullable();
        Map(x => x.ReferralDate);
        Map(x => x.Decision);
        Map(x => x.Reason);
        Map(x => x.StartDate);
        Map(x => x.EndDate);
    }
}

但是当我运行它并提交没有值的表单时,我收到以下验证错误:

# The ReferralDate field is required.
# The StartDate field is required.
# The EndDate field is required.

但我没有指定这些应该是必需的?!为什么决策和原因字段不抛出类似的验证错误?

任何人都可以对此有所了解吗?

我正在使用 .NET 4 和 MVC 2。

4

2 回答 2

3

Could you change this:

public virtual DateTime ReferralDate { get; set; } 

to

public virtual DateTime? ReferralDate { get; set; } 

You need to use nullable type for DateTime.

If you want to do the same for all other dates change them:

public class CaseInfo :IValidatableObject {        
    public virtual Guid Id { get; set; }     
    public virtual DateTime? ReferralDate { get; set; }     
    public virtual int Decision { get; set; } 
    public virtual string Reason { get; set; }     
    public virtual DateTime? StartDate { get; set; }     
    public virtual DateTime? EndDate { get; set; }      
    public IEnumerable<ValidationResult>

Validate(ValidationContextvalidationContext) {throw new NotImplementedException();} }

Check the MSDN documentation on datetime: http://msdn.microsoft.com/en-us/library/system.datetime(v=VS.90).aspx

You will notice that the values have a range, which do not include null, hence your validator fails. You will want to use the datetime nullable type.

于 2011-02-11T16:15:05.997 回答
2

DateTime 结构不可为空,因此它实际上是必需的。如果它可以为空,您应该使用Nullable<DateTime>[or的简写]。DateTime?

于 2011-02-11T16:14:09.680 回答