Domanda

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.

È stato utile?

Soluzione

This isn't necessarily a bad thing at all. It's actually better to do it here in the view where display is relevant than to do it in a controller or similar.

However, I share your concerns that it might not be the best approach.

The ASP.NET MVC solution to this problem is through the use of attributes. In particular, the use of the DisplayFormat attribute.

The problem that you're facing (and I've faced before) is that, although such things seem to belong in the view (because it's about how things are displayed), it quickly means that you're writing the same things over and over in many views, duplicating code.

With attributes like [DisplayFormat] you can decorate your view model properties with how you want them displayed.

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

For bonus points you can even create your own custom attributes and name them appropriately for less code duplication.

[Percentage]
public int Rate;
[Currency]
public int Cost;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top