Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between @Html.ValueFor(x=>x.PropertyName) and @Model.PropertyName

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

like image 724
Buffalo Avatar asked May 24 '13 15:05

Buffalo


People also ask

What is HTML HiddenFor in MVC?

The Html. HiddenFor<TModel, TProperty> extension method is a strongly typed extension method generates a hidden input element for the model property specified using a lambda expression. Visit docs.microsoft.com to know all the overloads of HiddenFor() method. Example: HiddenFor() in Razor View.

What is HTML EditorFor in MVC?

ASP.NET MVC includes the method that generates HTML input elements based on the datatype. The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.

What are HTML helpers in MVC?

In MVC, HTML Helper can be considered as a method that returns you a string. This string can describe the specific type of detail of your requirement. Example: We can utilize the HTML Helpers to perform standard HTML tags, for example HTML<input>, and any <img> tags.


2 Answers

@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"
like image 188
Buh Buh Avatar answered Oct 16 '22 12:10

Buh Buh


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.

like image 21
GSerg Avatar answered Oct 16 '22 11:10

GSerg