2014-11-14 75 views
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> 

回答

1

的方法,decleration想要一个函数作为参数,但你给它一个属性。

你可以尝试,而不是的foreach和使用:

@ Html.RecentDate(M => M [I] .LadtPostDate)

顺便说一句:你也可以使用自定义显示模板。

@model DateTime 

... Logic for displaying your date ... 

那么该视图将是类似的东西:(!昨晚小时,今天早上,刚刚发现了它)

​​3210
+0

我刚刚发现了答案。我认为你是对的,虽然为我工作的解决方案是@ Html.RecentDate(m => item.LastPostDate);谢谢! – GeoffM 2014-11-14 18:50:01

+0

看看编辑过的帖子。对于帮手,你可以使用For的东西来保留NamingConventions。 – Tobias 2014-11-14 18:52:15