将datetime格式化为视图中的shortdatestring

时间:2011-05-09 15:31:18

标签: asp.net asp.net-mvc-3

在我的模型中,我有;

public class ReportDetails 
{
    public DateTime? MailSent { get; set; }
    public DateTime? DateCompleted { get; set; }
}

在我的控制器中;

var query = (from u in SessionHandler.CurrentContext.LennoxSurveyResponses
                             join c in SessionHandler.CurrentContext.MailingListEntries on u.SurveyCode equals c.SurveyCode
                             join cl in SessionHandler.CurrentContext.MailingLists on c.MailingListId equals cl.MailingListId
                             join ch in SessionHandler.CurrentContext.Channels on cl.ChannelId equals ch.ChannelId
                             join cg in SessionHandler.CurrentContext.ChannelGroups on ch.ChannelGroupId equals cg.ChannelGroupId
                             where ch.OrganizationId == 8
                             && ch.ChannelId == model.ChannelId
                             select new ReportDetails
                             {
                                 MailSent = c.LetterDate,
                                 DateCompleted = c.EmailDate
                             });
            model.Report = query.ToList();

现在在我看来,我有

@foreach (var tr in Model.Report)
                {
                    <tr>
                        <td>@tr.MailSent
                        </td>
                        <td>@tr.DateCompleted
                        </td>
                    </tr>

显示结果时,MailSentDateCompleted同时包含日期和时间。我试图只显示没有时间的日期。如果我尝试@tr.MailSent.HasValue ? @tr.MailSent.Value.ToShortDateString() : @tr.MailSent;,那么我会收到错误 - Value cannot be null。我如何只显示日期部分。 MailSentDateCompleted都是可以为空的字段。提前谢谢。

2 个答案:

答案 0 :(得分:3)

您有两种选择:

一种扩展方法:

public static MvcHtmlString ShortDate(this DateTime? dateTime)
{
    if (dateTime.hasValue)
        return MvcHtmlString.Create(dateTime.ToShortDateString());
    else
        return MvcHtmlString.Create("Your other option");
}

View usage:
<td>@tr.MailSent.ShortDate()</td>

或内联:

@(tr.MailSent.HasValue ? @tr.MailSent.Value.ToShortDateString() : DateTime.Now.ToString())

或默认值

@tr.MailSent.GetValueOrDefault().ToShortDateString()

答案 1 :(得分:0)

在代码而不是视图中执行此操作:

select new ReportDetails
{
    MailSent = c.LetterDate.HasValue ? c.LetterDate.Value.ToShortDateString() : "",
    DateCompleted = c.EmailDate.HasValue ? c.EmailDate.Value.ToShortDateString() : "",
}

然后你不必担心炸毁Razor

<tr>
    <td>@tr.MailSent</td>
    <td>@tr.DateCompleted</td>
</tr>