开发者

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

开发者 https://www.devze.com 2023-04-10 21:20 出处:网络
I have a SmallDateTime field in my Sql Server 2008 database to store users Birthdays. On my \'Edit Profile\' web page, I have a standard textbox which I want to bind the \'Birthday\' date to (excludi

I have a SmallDateTime field in my Sql Server 2008 database to store users Birthdays.

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). 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 val开发者_运维技巧ue specified complies to dd/mm/yyyy, and any deviation from that is highlighted via my existing validation summary on the page.

How do I go about:

a) configuring the Birthday property in my ViewModel to display in dd/mm/yyyy format (excluding the time).

b) validate Birthday (based on dd/mm/yyyy format) when the user submits the form?


[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

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.

EDIT: for the validation stuff see this:other question on SO


a) you can use .ToShortDateString to render your datetime without time. Format still depends on globalization defaults.

b) to validate, you could do it with Data Annotations on your model like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号