r.r
r.r

Reputation: 7153

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?

Upvotes: 8

Views: 19056

Answers (2)

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

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.

Upvotes: 10

davehauser
davehauser

Reputation: 5944

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

Upvotes: 13

Related Questions