2

My question is about working with MVC Razor view engine.

To display data it is allowed to use some C# functions as inline functions e.g.

<td>@(Html.DisplayFor(m=>row.CurrencyFrom).ToString().Substring(3,3))</td>
<td>@(Html.DisplayFor(m=>row.rate).ToString("0.#####"))</td>

Is it a good approach to use these sort of functions here. I am sorry I am new to MVC and Razor but it looks like it is against principal of separation. Please guide me what is correct way to do these sort of formatting and functionalists. Not sure is there a sort of best practice or guidline available on it ?

Much thanks for your guidance.

4

1 回答 1

2

这根本不一定是坏事。实际上,在显示相关的视图中执行此操作比在控制器或类似设备中执行此操作要好。

但是,我与您一样担心这可能不是最好的方法。

对此问题的 ASP.NET MVC 解决方案是通过使用属性。特别是DisplayFormat属性的使用。

您面临的问题(我之前也遇到过)是,虽然这些东西似乎属于视图(因为它是关于事物的显示方式),但它很快意味着您正在写相同的东西并且在许多视图中,重复代码。

使用像[DisplayFormat]您这样的属性,您可以使用您希望它们显示的方式来装饰您的视图模型属性。

[DisplayFormat(DataFormatString="{0:C}")]
public object StandardCost;

对于奖励积分,您甚至可以创建自己的自定义属性并适当地命名它们以减少代码重复。

[Percentage]
public int Rate;
[Currency]
public int Cost;
于 2013-10-17T00:05:48.403 回答