【发布时间】:2014-11-21 15:30:13
【问题描述】:
尝试使用自定义 HtmlHelper 输出 DateTime,使其返回“今天 XX:YY”、“昨天 XX:YY”或“时间日期”(具体格式在此阶段并不重要 -只需要它返回一个字符串)。
显然我错过了一些重要和基本的东西,应该知道的更好!
我的助手:
public static MvcHtmlString RecentDate<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
if (metadata.Model != null && metadata.Model as DateTime? != null)
{
DateTime dt = (DateTime)metadata.Model;
if (dt.Date == DateTime.Now.Date)
{
return MvcHtmlString.Create("Today " + dt.ToShortTimeString());
}
else if (dt.Date == DateTime.Now.AddDays(-1).Date)
{
return MvcHtmlString.Create("Yesterday " + dt.ToShortTimeString());
}
else
{
return MvcHtmlString.Create(dt.ToShortDateString() + " at " + dt.ToShortTimeString());
}
}
return MvcHtmlString.Create("Never");
}
cshtml:
@model xxx.Models.ForumLatestPosts
@{
ViewBag.Title = "Latest Posts";
}
<h2>@ViewBag.Title.</h2>
<div>
<hr />
<dl class="dl-horizontal">
<dt>Latest Posts</dt>
<dd>
<table>
@foreach (var item in Model.Threads)
{
<tr>
<td>
@Html.ActionLink(item.Title, "Thread", new { id = item.Id })
</td>
<td>
@item.Title
</td>
<td>
@Html.RecentDate(item.LastPostDate);
</td>
</tr>
}
</table>
</dd>
</dl>
</div>
错误:
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0411: The type arguments for method 'xxx.HtmlHelpers.RecentDate<TModel,TValue>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TValue>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Source Error:
Line 22: </td>
Line 23: <td>
**Line 24: @Html.RecentDate(item.LastPostDate);**
Line 25: </td>
Line 26: </tr>
【问题讨论】:
标签: asp.net-mvc razor