21
@Html.ValueFor(x=>x.PropertyName) 
@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?

2 Answers 2

33

@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:

[DisplayFormat(DataFormatString="{0:C}")]
public decimal PropertyName = 1234.56;

@Html.ValueFor(x => x.PropertyName)  =>  "£1,234.56"
@Model.PropertyName                  =>  "1234.56"
1
  • 2
    That's a great example. Thank you!
    – Buffalo
    May 28, 2013 at 15:37
21

ValueFor will invoke the template that exists for rendering the type that the property has. By default this template may be as simple as ToString(), but you can define anything as the template.

@Model.PropertyName will simply present the value as string.

1
  • From the documentation for ValueFor : "Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates."
    – dom
    May 24, 2013 at 15:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.