【问题标题】:Calculate age in Razor(ASP.NET mvc)在 Razor 中计算年龄(ASP.NET mvc)
【发布时间】:2017-05-26 04:06:25
【问题描述】:

我有一个带表的视图

这是视图的代码:

 @foreach (var item in Model)
{
    <tr>
        <td class="point">
            @(rowNo += 1)
        </td>
        <td class="FIO" style="text-align: center; font-size: 16px; cursor:pointer">@Html.DisplayFor(modelItem => item.FIO) @Html.Hidden("clientEmail", item.FIO)</td>

        <td style="text-align: center; font-size: 16px;">
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td style="text-align: center; font-size: 16px;">
            @Html.DisplayFor(modelItem => item.City)
        </td>
        <td style="text-align: center; font-size: 16px;">
            @Html.DisplayFor(modelItem => item.Birthday)
        </td>
        <td style="text-align: center; font-size: 16px;">
            @Html.DisplayFor(modelItem => item.Salary)
        </td>
        <td style="text-align: center; font-size: 16px;">
            @Html.DisplayFor(modelItem => item.English)
        </td>
      <td style="text-align: end;">
            <a href='@Url.Action("Edit", "Interwier", new {id = item.Interwier_id})'>
                <img src='@Url.Content("~/Images/Edit.png")' />
            </a>
            <a href='@Url.Action("Delete", "Interwier", new {id = item.Interwier_id})'>
                <img src='@Url.Content("~/Images/Delete.png")' />
            </a>
        </td>
    </tr>
}

这段代码是关于年龄的:

<td style="text-align: center; font-size: 16px;">
    @Html.DisplayFor(modelItem => item.Birthday)
</td>

它从数据库返回我的年份。我需要显示年龄。

我怎样才能正确地做到这一点?

【问题讨论】:

  • 通过向计算它的模型添加一个属性?
  • 我可以在前端而不是后端执行此操作吗?@SamiKuhmonen
  • 为什么在前端?不好的做法。正如 sami 所提到的......这是正确的
  • 当然,如果需要,您可以在视图中为其添加计算。但是你为什么会呢?
  • 好的。我怎么能在后端做到这一点? @SamiKuhmonen 为年龄添加新属性并计算“现在 - 年”?@SamiKuhmonen

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

根据您的描述,您的Birthday 是一个年份值,您可以:

首先在模型中添加一个新属性,用于生成Age

public class ModelName
{
    // other properties
    // original Birthday property
    public int Birthday {get;set;}

    // get age by subtracting current year with Birthday year.
    public int Aget {get {return DateTime.Now.Year - Birthday;}}
}

那么在你看来

将显示 Birthday 更改为 Age

 <td style="text-align: center; font-size: 16px;">
            @Html.DisplayFor(modelItem => item.Age)
 </td>

【讨论】:

  • 谢谢它的帮助!
猜你喜欢
  • 2017-09-15
  • 1970-01-01
  • 2014-11-16
  • 2017-05-26
  • 2017-08-08
  • 2012-03-26
  • 1970-01-01
  • 2020-12-28
  • 2016-03-20
相关资源
最近更新 更多