I’m using a loop as below to render a label and editor for each property on a view model:
@{
var properties = ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !pm.IsComplexType && !ViewData.TemplateInfo.Visited(pm));
}
@foreach (var prop in properties)
{
<li>
<div class="form-line">
@{
if (prop.HideSurroundingHtml)
{
@Html.Editor(prop.DisplayName ?? prop.PropertyName)
}
else
{
@Html.Label((prop.IsRequired ? "* " : "") + (prop.DisplayName ?? prop.PropertyName))
@Html.Editor(prop.PropertyName)
}
}
</div>
</li>
}
And the model:
[Required]
[Display(Name = "Status")]
[UIHint("DropDown", "MVC", "SelectListName", "StatusSelectList")]
public Guid StatusId { get; set; }
[Required]
[Display(Name = "Emp Number")]
public string RefNum { get; set; }
[Required]
public string Surname { get; set; }
When I use a display name of “Emp. No.”, a label doesn’t get rendered at all. When I use a display name of “Emp. Number”, only a “Number” label gets rendered. Only when I use a display name of “Emp Number”, without any full stops, does my full, expected label get rendered. What is going on here?
You are using the wrong overload of the Html.Label helper. The first argument represents an expression that will point to the editor so that the
forattribute of the label points to the corresponding input field. The second argument allows you to set the label text. Try like this: