简体   繁体   English

ASP.NET MVC 3与html文本框控件的绑定和验证日期

[英]ASP.NET MVC 3 Binding & Validating Date to html textbox control

I have a SmallDateTime field in my Sql Server 2008 database to store users Birthdays. 我在Sql Server 2008数据库中有一个SmallDateTime字段,用于存储用户生日。

On my 'Edit Profile' web page, I have a standard textbox which I want to bind the 'Birthday' date to (excluding the time as this is not required). 在“编辑个人资料”网页上,我有一个标准的textbox ,我要将“生日”日期绑定到该textbox (不包括时间,因为这不是必需的)。 At present I am binding to the textbox but it is rendering the full Date and Time. 目前,我绑定到文本框,但它正在呈现完整的日期和时间。

In addition, when the user updates their profile, I want to be able to validate the Birthday textbox, ensuring that the value specified complies to dd/mm/yyyy , and any deviation from that is highlighted via my existing validation summary on the page. 另外,当用户更新其个人资料时,我希望能够验证“生日”文本框,确保指定的值符合dd/mm/yyyy ,并通过我现有的验证摘要在页面上突出显示与该值的任何偏差。

How do I go about: 我该怎么做:

a) configuring the Birthday property in my ViewModel to display in dd/mm/yyyy format (excluding the time). a)在我的ViewModel中配置Birthday属性,使其以dd/mm/yyyy格式显示(不包括时间)。

b) validate Birthday (based on dd/mm/yyyy format) when the user submits the form? b)在用户提交表单时验证生日(基于dd/mm/yyyy格式)?

[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
public DateTime DateOfBirth { get; set; }

This should give you the automatic formatting on the field (without you having to manually do it) and also the validation. 这应该使您可以在字段上进行自动格式化(而无需手动进行)和验证。

I usually use a string property paired with the DateTime object, something like 我通常使用与DateTime对象配对的字符串属性,例如

public string MyDateStr 
{
   get 
   {
       return MyDateDate == null ? "" : MyDateDate.ToShortDateString();
   }
   set
   {
      // Usually a tryParse for the string value
   }
}

I know that is not the canonical way, but up to now, is the fastest I've found. 我知道这不是规范的方法,但是到目前为止,这是我发现的最快方法。

HTH 高温超导

M. M.

EDIT: for the validation stuff see this: other question on SO 编辑:对于验证的东西,请参阅此: SO上的其他问题

a) you can use .ToShortDateString to render your datetime without time. a)您可以使用.ToShortDateString来呈现没有时间的日期时间。 Format still depends on globalization defaults. 格式仍然取决于全球化默认值。

b) to validate, you could do it with Data Annotations on your model like this: b)进行验证,您可以使用模型上的数据注释来做到这一点,如下所示:

[DataType(DataType.DateTime, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy")]
public DateTime Birthday { get; set; }

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

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