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

后端 未结 1 862
野性不改
野性不改 2021-02-02 11:52

I have a class

public class Item
{
    public int ItemId { get; set; }

    [Required(ErrorMessage = \"Category is required\")]
    [Range(1, int.MaxValue, Error         


        
相关标签:
1条回答
  • 2021-02-02 12:23

    Almost there. :)

    The DisplayNameFor shows the name of the property or the 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) would show 'Current name'.

    @Html.DisplayNameFor(m => m.Price) would just show Price.

    Note that you can also localize the display attribute like this:

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

    Which in turn will look in the MyResources resc file. (If setup is done correctly).

    The Html.DisplayFor shows the value of the field.

    0 讨论(0)
提交回复
热议问题