Html.LabelFor Specified Text [ASP.NET MVC 2]

Has anyone figured out how to specify text when using Html.LabelFor(c=>c.MyField) . It's just MyField , it may not be the right name to display on the screen, you may need a "Super-Fantastic Field", but there seems to be no overload.

Any ideas?

+72
asp.net-mvc asp.net-mvc-2
Aug 21 '09 at 16:09
source share
7 answers

You are using System.ComponentModel.DataAnnotations.DisplayAttribute :

 [Display(Name = "My Field")] public string MyField { get; set; } 

Setting the ResourceType property in your attribute will allow you to use the resource file.

(Prior to .NET 4, use System.ComponentModel.DisplayNameAttribute with the caveat that the display name should be a compile-time constant.)

+128
Aug 21 '09 at 17:33
source share

A simple solution is to simply add the following to your view:

 @Html.LabelFor(c=>c.MyField, "My Field") 
+40
Jul 31 '12 at 16:28
source share

A new overload has appeared in MVC 3, so you can specify a special test for the labelfor helper.

+26
Nov 24 '10 at 5:20
source share

I have not downloaded v2 yet, so I can’t test, but I believe that it works like DynamicData, in which case you would do something similar in your model:

 [Display(Name = "The Super Fantastic Field")] public string MyField {get;set;} 
+3
Aug 21 '09 at 16:24
source share

I have not tested CP1 yet, but I read its version of Scott, and it looks like I remember that the code was created by T4. I suppose you can always change this, but I suspect that they will provide overloads in CP2.

Edit: the source is always available, and you can simply modify the method, change the T4 generator, and you will be well off. Also put a ticket or request (in some way) for this mod so that it works in the next version.

0
Aug 21 '09 at 16:17
source share

There are 5 overloads. A few offer the second parameter "string labelText", which you would set in the "Super-fantastic field".

0
Apr 13 '14 at 21:40
source share

There are two ways: 1 "direct annotations"
2 "Annotatins with a resource"
Direct annotations

 [Display(Name = "My Field")] public string MyField { get; set; } 

Annotatinos with resource

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

The second way is to add a value to the resource file, which is probably called Resource.resx .
Use that is suitable for your purpose.

0
Jan 31 '17 at 16:56
source share



All Articles