Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to show some text in html.LabelFor?

I am doing int like this:

Hello <%=  Html.LabelFor(user => user.UserName)%>

But iam getting not a value which is in Property but something strange like this:

Hello User Name,

How can do it to give some value in label out?

like image 910
r.r Avatar asked Sep 07 '10 15:09

r.r


2 Answers

Add DataAnnotations to your model/viewmodel:

public class Customer
{
    [Display(Name = "Email Address", Description = "An email address is needed to provide notifications about the order.")]
    public string EmailAddress { get; set; }

    [Display(ResourceType=typeof(DisplayResources), Name="LName", Description="LNameDescription")]
    public string LastName { get; set; }
}

Source: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute(v=VS.95).aspx

If you don't provide a display name by the DisplayAttribute then Html.EditorFor(...) uses the properties name, spliting it on upper case letters:

PropertyName --> Label text
Email --> Email
EmailAdress --> Email Address

like image 187
davehauser Avatar answered Nov 15 '22 21:11

davehauser


The reason for this is because Html.LabelFor will do just that - create a label for the property. In this case, it is producing a label of 'User Name' since the property name is UserName.

You just need to look at the model (or whatever your passing to the view) to return the property value: Html.Encode(Model.UserName)

Update (since this was nearly 3 years ago but people have recently upvoted):

You can just use <%: Model.UserName %> to get the HTML encoded value (<%= writes it as raw and <%: writes it encoded).

If you're using a Razor view engine, then @Model.Username will write it out already encoded.

like image 21
Jonathon Bolster Avatar answered Nov 15 '22 22:11

Jonathon Bolster