format datetime to shortdatestring in view
In my model, i have;
public class ReportDetails
{
public DateTime? MailSent { get; set; }
public DateTime? DateCompleted { get; set; }
}
In my controller;
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();
Now in my view, I have
@foreach (var tr开发者_Go百科 in Model.Report)
{
<tr>
<td>@tr.MailSent
</td>
<td>@tr.DateCompleted
</td>
</tr>
When the results are displayed, the MailSent
and DateCompleted
have both date and time. I am trying to just display the Date without the Time. If I try @tr.MailSent.HasValue ? @tr.MailSent.Value.ToShortDateString() : @tr.MailSent;
then i get an error - Value cannot be null
. How would i display just the date part. Both MailSent
and DateCompleted
are nullable fields. Thanks in advance.
You have two options:
an extension method:
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>
or inline:
@(tr.MailSent.HasValue ? @tr.MailSent.Value.ToShortDateString() : DateTime.Now.ToString())
or a default value
@tr.MailSent.GetValueOrDefault().ToShortDateString()
Do this in code rather than the view:
select new ReportDetails
{
MailSent = c.LetterDate.HasValue ? c.LetterDate.Value.ToShortDateString() : "",
DateCompleted = c.EmailDate.HasValue ? c.EmailDate.Value.ToShortDateString() : "",
}
Then you don't have to worry about blowing up Razor
<tr>
<td>@tr.MailSent</td>
<td>@tr.DateCompleted</td>
</tr>
精彩评论