HtmlHelper用于自定义日期

时间:2014-11-14 18:02:37

标签: asp.net-mvc razor

尝试使用自定义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>

1 个答案:

答案 0 :(得分:1)

method-decleration想要一个函数作为参数,但你给它一个属性。

你可以尝试而不是foreach并使用:

@ Html.RecentDate(m =&gt; m [i] .LadtPostDate)

顺便说一下:您还可以使用自定义显示模板。

@model DateTime

... Logic for displaying your date ...

然后视图会是这样的:

@Html.EditorFor(m=>m.LastPostDate, "NameOfTheEditorTemplate")