Code:
<% foreach (var item in Model) { %>
<td>
<%= Html.Encode(item.BirthDate) %>开发者_如何转开发
</td>
<% } %>
display this: 8/24/2009 12:00:00 AM but I need only date (8/24/2009). It is possible to do without any formating in controller action
There are a couple of ways to go about it. If you're using MVC 2, you could use a DisplayTemplate. Just put a DateTime.ascx file in the folder called /Views/Shared/DisplayTemplates and the line of code it would have in it is:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%: Model.HasValue ? Model.Value.ToShortDateString() : string.Empty %>
(Note: if you use the <%: syntax then you don't need the Html.Encode() because <%: does the HTML encoding for you - but that's only if you're using VS2010. If you're using MVC 2 with VS2008, then stick with the Html.Encode() for this part) Then in your view you would simply do this:
<%: Html.DisplayFor(m => m.BirthDate) %>
That will change the format to only have the Date for all DateTime's in your application. Of course you could put that directly in the view as well. But the DisplayTemplate will change it for all other DateTime's as well and you won't have to concern yourself with it in the view since it happens for your automatically.
If BirthDate is string datatype
<%= Html.Encode(!String.IsNullOrEmpty(item.BirthDate) ?
Convert.ToDateTime(item.BirthDate).ToShortDateString() : item.BirthDate) %>
If BirthDate is datetime datatype
<%=Html.Encode(String.Format("{0:MM/dd/yyyy}", item.BirthDate))%>
I would say that formatting is a responsibility of the view, not the controller, so format the output like this:
<% foreach (var item in Model) { %>
<td>
<%= Html.Encode(item.BirthDate.ToShortDateString() %>
</td>
<% } %>
If item.BirthDate is type of DateTime you can use ToShortDateString() method:
item.BirthDate.ToShortDateString();
<% foreach (var item in Model) { %>
<td>
<%= Html.Encode(item.BirthDate.ToString("MM/dd/yyyy")) %>
</td>
<% } %>
精彩评论