c# - ASP.net 验证 : why do my DateTime fields also flag up as required?

标签 c# asp.net-mvc asp.net-mvc-2-validation

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

Controller 代码如下:

[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。

最佳答案

你能改变这个吗:

public virtual DateTime ReferralDate { get; set; } 

public virtual DateTime? ReferralDate { get; set; } 

您需要为 DateTime 使用可空类型。

如果您想对所有其他日期执行相同的操作,请更改它们:

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();} }

查看有关日期时间的 MSDN 文档:http://msdn.microsoft.com/en-us/library/system.datetime(v=VS.90).aspx

您会注意到这些值有一个范围,其中不包括 null,因此您的验证器失败了。您将需要使用 datetime 可为 null 的类型。

关于c# - ASP.net 验证 : why do my DateTime fields also flag up as required?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4971328/

相关文章:

c# - 循环中从 CryptoStream 获取字符串

c# - Entity Framework 原始 SQL 查询

c# - 如何利用 tesseract 中所有可用的语言?

c# - MVC 错误 : Object reference not set to an instance of an object

asp.net-mvc - 执行验证 : ViewModel, 模型或 Controller 的推荐位置是什么?

asp.net-mvc - 自定义验证属性不适用于客户端,仅适用于服务器

c# - 获取旋转的 GraphicsPath 中最左边的点

asp.net-mvc - 什么是 ASP.Net MVC 中的 _Viewstart

c# - 在 MVC 应用程序上自动执行防伪 token 验证

c# - ASPNET MVC - 为什么 ModelState.IsValid false "The x field is required"当该字段确实有值时?