在视图中处理逻辑和常量 [英] Handling logic and constants in the View

查看:47
本文介绍了在视图中处理逻辑和常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 View 上显示了一个日期,该日期显示了用户登录的最后日期.他们可能从未这样做过.因此它作为 nullable DateTime 传递.

I have a date that gets displayed on my View that shows the last date a user logged in. They may have never done so. So it's passed as a nullable DateTime.

在用户界面上,我将其显示如下:

On the UI, I display it like this:

<td>@(u.LastVisit != null ? u.LastVisit.Value.ToString("dd-MMM-yyyy") : "Not yet")</td>

但是我对此有一些疑问,认为这可能是不好的做法.

But I have a few issues with this and think it might be bad practice.

首先,视图现在具有逻辑.(如果为null,则显示"Not Yet",否则显示日期).视图还规定了日期格式.该格式已经作为常量存储在Constants文件中,可以从我的控制器访问.文字"Not Yet"也应该是一个常量.

Firstly, the view now has logic. (If null, show "Not Yet", else show the date). The View also dictates the date format. That format is already stored as a constant in a Constants file, accessible from my controller. And the text "Not Yet" should probably be a constant as well.

我能看到的唯一方法是将String返回到UI,并将该逻辑移至控制器.但这是正确的方法吗?

The only way I can see around this, is to return a String to the UI, and move that logic to the controller. But is that the right way to do this?

推荐答案

您可以将 [DisplayFormat] 属性应用于属性,并设置 DataFormatString NullDisplayText 属性,例如

You can apply a [DisplayFormat] attribute to the property and set the DataFormatString and NullDisplayText properties, for example

[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", NullDisplayText = "Not yet")]
public DateTime? LastVisit { get; set; }

如果您已经为格式定义了一些常量,则可以使用(例如) DataFormatString = yourAssembly.Constants.DateFormat ,其中将 DateFormat 定义为

If you have already defined some constants for the format then you can use (for example) DataFormatString = yourAssembly.Constants.DateFormat where DateFormat is defined as

public const string DateFormat = "{0:dd-MMM-yyyy}";

,然后在视图中使用 DisplayFor()

@foreach(var u in Model)
{
    @Html.DisplayFor(m => u.LastVisit)
}

这篇关于在视图中处理逻辑和常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆