C# – the difference between @Html.ValueFor(x=>x.PropertyName) and @Model.PropertyName



It seems like these two Razor commands do the exact same thing. Is there any special circumstance or benefit of using one over the other?

Best Solution

@Html.ValueFor(x => x.PropertyName) invokes a lot a code and reflection under the hood.
It will allow you to customize the way the value is presented, and then have a consistent format across your whole site. For example, if your property is decorated with DisplayFormatAttribute.

@Model.PropertyName is literally getting the value of the property directly, calling ToString() on it, and HTML escaping the result. No other formatting will take place.


To illustrate, you might see this:

public decimal PropertyName = 1234.56;

@Html.ValueFor(x => x.PropertyName)  =>  "£1,234.56"
@Model.PropertyName                  =>  "1234.56"