Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between DisplayFor and ValueFor

I'm wondering what the difference is between ValueFor, which I didn't know until recently, and DisplayFor, which I've been using for displaying values.

I set up a test project in which I created a Model with 2 properties:

public class TestModel
{
    [Display(Name = "Montant")]
    [DisplayFormat(DataFormatString = "{0:C2}")]
    public Decimal Amount
    {
        get;
        set;
    }

    [Display(Name = "Date d'achat")]
    [DataType(DataType.Date)]
    public DateTime Date
    {
        get;
        set;
    }
}

Here's the result I'm getting:

TestModel model = new TestModel
{
    Amount = 1234.333M,
    Date = DateTime.Today.AddDays(-10)
};

@Html.DisplayFor(x => x.Amout)   => "1 234,33 €"
@Html.ValueFor(x => x.Amount)    => "1234,333"

@Html.DisplayFor(x => x.Date)    => "23/03/2014"
@Html.ValueFor(x => x.Date)      => "23/03/2014 00:00:00"

From what I see, there's no advantage of using ValueFor instead of @Model.PropertyName

While looking for answers, I stumbled on this question where the most upvoted answer, while not voted best answer, gives different results than mine.

Anyone knows why we get different results and what is the real use of ValueFor?

like image 514
Mickaël Derriey Avatar asked Apr 02 '14 11:04

Mickaël Derriey


People also ask

What is DisplayFor?

Html. DisplayFor() will render the DisplayTemplate that matches the property's type.

What is the difference between DisplayNameFor and DisplayFor in MVC?

DisplayFor displays the value for the model item and DisplayNameFor simply displays the name of the property?

What is HTML DisplayFor?

DisplayFor() The DisplayFor() helper method is a strongly typed extension method. It generates a html string for the model object property specified using a lambda expression.


1 Answers

First I've heard of ValueFor as well....however, looking at the source it would appear that ValueFor does a simple render using only the metadata against the model ignoring any associated templates (built-in or custom).


Further digging shows that in actual fact, the result of ValueFor is the equivalent to calling String.Format or Convert.ToString using the current culture depending on whether you provide a custom format

@Html.ValueFor(x => x.Amount) = Convert.ToString(x.Amount, CultureInfo.CurrentCulture)
@Html.ValueFor(x => x.Amount, "0.00") = String.Format(x.Amount, "0.00", CultureInfo.CurrentCulture)
like image 198
James Avatar answered Sep 18 '22 17:09

James