Question

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?

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top