u936293
u936293

Reputation: 16224

LabelFor is showing property name instead of Display attribute

My model is:

public class MyMessage
{
    [Required, Display(Name= "Recipient Id")]
    public string Recipient;
    [Required, Display(Name ="Message")]
    public string Text;
}

My view is:

@model MyMessage

@Html.LabelFor(m=>m.Recipient)
@Html.TextBoxFor(m=>m.Recipient)
<br/>
@Html.LabelFor(m => m.Text)
@Html.TextBoxFor(m => m.Text)

The rendered output is showing the property name instead of the Display attribute. What have I done wrong?

Upvotes: 2

Views: 1340

Answers (1)

user3559349
user3559349

Reputation:

Change the fields in your model to properties

public class MyMessage
{
    [Required, Display(Name= "Recipient Id")]
    public string Recipient { get; set; }
    [Required, Display(Name ="Message")]
    public string Text { get; set; }
}

The ModelMetadata.DisplayName is not set for fields. And you need to do this anyway because the DefaultModelBinder does not set the value of fields, so when you submit the form, the values of Recipient and Text would have been null despite what text you entered in the textboxes and ModelState would have been invalid because of the [Required] attributes

Upvotes: 3

Related Questions