简体   繁体   English

禁用ASP.NET MVC验证

[英]Disable ASP.NET MVC validation

I have a simple ViewModel class in my asp.net mvc application. 我在asp.net mvc应用程序中有一个简单的ViewModel类。

public class DestinationViewModel
{
     [Display(Name = "Country")]
     [some validation attributes]
     public string CountryName { get; set; }

     [Display(Name = "Destination")]
     [some validation attributes]
     public string DestinationName { get; set; }

     public DateTime? DepartureDate { get; set; }

     public DateTime? ArrivalDate { get; set; }
}

When i pass data to controller my application shows validation errors on invalid departure and arrival date. 当我将数据传递给控制器​​时,我的应用程序会在无效的出发和到达日期上显示验证错误。 But i donnt want such behavior. 但是我不想要这样的行为。 Is there any way(attribute) to disable validation only on DepartureDate and ArrivalDate fields? 有什么方法(属性)仅在DepartureDateArrivalDate字段上禁用验证?

The MVC data binder will attempt to convert which ever value you put in your input field to it's corresponding ViewModel type. MVC数据绑定程序将尝试将您在输入字段中输入的值转换为对应的ViewModel类型。 In your scenario, you are passing " 21321 " which obviously isn't going to work as it's not valid Date/Time. 在您的方案中,您传递的是“ 21321 ”,这显然无效,因为它不是有效的日期/时间。

Either pass a valid DateTime string value or leave it empty (as the field is nullable). 传递有效的DateTime字符串值或将其保留为空(因为该字段可为空)。

Tip - It's usually a good idea from a users point of view to make date fields readonly and provide a date picker of some sort to avoid issues with manually entering valid date formats. 提示-从用户的角度来看,通常最好将日期字段设置为只读,并提供某种日期选择器,以避免手动输入有效日期格式出现问题。

If you want to write anything you want, then use string , not DateTime? 如果要编写任何内容,请使用string ,而不要使用DateTime? or use one of this solutions: 或使用以下解决方案之一:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM