9

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?

Community
  • 1
  • 1
Mickaël Derriey
  • 12,796
  • 1
  • 53
  • 57

1 Answers1

6

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)
James
  • 80,725
  • 18
  • 167
  • 237
  • 1
    How would you explain that the metadata (`DataType` and `DisplayFormat`) is not used **at all** when I use `ValueFor` then? – Mickaël Derriey Apr 02 '14 at 12:27
  • 1
    @mickaeld although the source indicates it *should* be using the metadata - in actual fact it doesn't. If you follow the source path it calls `HtmlHelper.FormatValue` which internally calls `ViewDataDictionary.FormatValueInternal` which in turn just calls `Convert.ToString` or `String.Format` depending on whether you have supplied a custom format parameter or not. I have revised my answer – James Apr 02 '14 at 12:49
  • 1
    @mickaeld: You should only use ValueFor if you are building your own HTML helper extensions. – Jakob Christensen Apr 02 '14 at 13:50
  • @JakobChristensen I'm not sure the method would have been exposed as an extension method if it was meant to be used **only** in custom HTML helper methods. Looks like it's just useful if you want to easily apply formatting when displaying a raw value. – Mickaël Derriey Apr 03 '14 at 09:11