0
试图使用自定义HtmlHelper来输出一个DateTime,使其返回“今天在XX:YY”,“昨天在XX:YY”或“时间日期”(确切格式无关紧要在这个阶段 - 只需要它返回一个字符串)。HtmlHelper自定义日期
显然我错过了一些重要和基本的东西,应该知道更好!
我的助手:
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>
我刚刚发现了答案。我认为你是对的,虽然为我工作的解决方案是@ Html.RecentDate(m => item.LastPostDate);谢谢! – GeoffM 2014-11-14 18:50:01
看看编辑过的帖子。对于帮手,你可以使用For的东西来保留NamingConventions。 – Tobias 2014-11-14 18:52:15