What is a simple explanation for displayfor and displaynamefor in asp.net?

I have a class

public class Item { public int ItemId { get; set; } [Required(ErrorMessage = "Category is required")] [Range(1, int.MaxValue, ErrorMessage = "Category is required")] public int CategoryId { get; set; } [Display(Name = "Current password")] [Required(ErrorMessage = "Name is required")] [StringLength(160)] public string Name { get; set; } [Required(ErrorMessage = "Price is required")] [Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")] public decimal Price { get; set; } public virtual Category Category { get; set; } } 

In my controller, I pass an instance of this for viewing

 public ActionResult Index() { var model = new Item { CategoryId = 1, Name = "aaa", Price = 2 }; return View("Index", model); } 

then I will try to display the name using

 @model GenericShop.Models.Item <p> @Html.DisplayNameFor(m => m.Name) </p> 

and get the following error

Compiler error message: CS1061: "System.Web.Mvc.HtmlHelper" does not contain a definition of "DisplayNameFor" and the extension method "DisplayNameFor" accepts the first argument of the type "System.Web.Mvc.HtmlHelper" can be found (you are missing the using or directive assembly links?)

@Html.DisplayFor(m => m.Name) works fine, but I just can't figure out why

@Html.DisplayNameFor(m => m.Name) does not work.

DisplayFor display a value for a model element, and DisplayNameFor just display a property name?

+6
source share
1 answer

Almost there. :)

DisplayNameFor displays the property name or string defined in the display attribute for the property.

 public class Item { public int ItemId { get; set; } [Display(Name = "Current name")] [Required(ErrorMessage = "Name is required")] [StringLength(160)] public string Name { get; set; } [Required(ErrorMessage = "Price is required")] [Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")] public decimal Price { get; set; } } 

Then @Html.DisplayNameFor(m => m.Name) display "Current Name".

@Html.DisplayNameFor(m => m.Price) will just show the price.

Note that you can also localize the display attribute as follows:

 [Display(ResourceType = typeof(MyResources), Name = "Name")] public string Name{ get; set; } 

Which, in turn, will look in the resc file MyResources. (If the setting is correct).

Html.DisplayFor shows the value of the field.

+14
source

All Articles