开发者

How to format a date in a view for two-way binding in MVC 2?

So let's say I have a view that access a date:

<%= Html.TextBoxFor(model => Model.Birth开发者_Go百科day) %>

How do I have my view dictate how that date is formatted? I'd like to use common formatting options, and it's important that this is 2-way (both for display and data-entry).


In your model, you could use System.ComponentModel.DataAnnotations metadata to specify the format you want the property in. e.g.

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

Then, in your view, use:
<%= Html.EditorFor(model => model.Birthday) %>

Unfortunately, the regular HTML Helpers don't respect the metadata, so you have to use Html.EditorFor.


Use a specific ViewModel class that has a string in the format you want for the birthday and use that to display in the textbox. When you post the form, if you are using default binding for the domain object itself, it should parse the string for you. If you are using a ViewModel, you'll have to parse it upon posting the form.


I was kind of surprised to see that you can't just throw a format string in Html.EditorFor(). I've sinced starting using EditorTemplates.

Create a directory structure in your solution.

Views > Shared > EditorTemplates

Add a new MVC 2 User Control in the EditorTemplates folder and name it DateTime.ascx. Html.EditorFor(DateTime) will now use this user control for display.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>
<%= Html.TextBox(string.Empty, (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty)) %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜