Displaynamefor and Displayfor

Asked

Viewed 2,426 times

2

Studying about ASP.NET MVC, I came across the following lines of code:

@Html.DisplayNameFor(model => model.Title)
@Html.DisplayFor(model => model.Title)

I can’t understand the difference between using DisplayNameFor and DisplayFor.

2 answers

4


@Html.DisplayNameFor(model => model.Title) //mostra Title
@Html.DisplayFor(model => model.Title) //mostra o conteúdo de Title

Almost always wants to use the DisplayFor.

In fact the DisplayNameFor shows the name of the property which may be the name it was declared or can use a different name annotated with an attribute. It can be useful when you want to show a description of what the content is. As we do not speak English and we do not use mnemonics almost always the name of the property is not suitable. But if you have an annotation of the name then it can function as a label content. There are those who prefer to have a label separate or defined in view since it can have a context. There are those who prefer to have this link of the property with their name through Display().

To write down a name can do so in the template:

public class Livro {
    [Display(Name = "Tíulo do livro")]
    public string Title{ get; }
}

I put in the Github for future reference.

It’s a lot like the LabelFor.

3

I went through that example:

public class Teste
{
    [Display(Name = "current name")]
    public string Nome { get { return "teste"; } }
}

Using @Html.DisplayNameFor(model => model.Nome) would display the property name Nome or (in this case) the description placed on the property Display (Current name). @Html.DisplayFor(model => model.Title) displays the property value (test)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.