DevDave
DevDave

Reputation: 6898

Conflict with @Html.LabelFor and W3C Validator?

I have a model that I am using to present an index of a model from a database and have given a display name to some of the rows that may need spaces in them, (I.e. "weekstarting" in a db would be given a display name of "Week Starting").

So I set the display name for my model like this:

 [DisplayName("Week Starting")]
    public DateTime WeekStarting { get; set; }

and then in the table headers for my table I use the following line of code to display the field name using its given display name:

@Html.LabelFor(x => x.First().WeekStarting)

The above all works fine. But I am using the W3C validator and it is giving me the following error for the example I have given:

The for attribute of the label element must refer to a form control.

Forgive me if it is obvious but what am I doing wrong here? I am not using a form I am simply displaying an index of items in a table. I have tried to look for an answer and saw someone suggest that the form controls being referred to need ids (even though I'm not using a form) but this would not be applicable in this instance because if I tried to set an id in the index it would be duplicated with each item in the index:

  foreach (var item in Model.Tbms)
{
<tr><td>@item.value</td><tr>.... would be repeated for each item, and also unsure where I would put the id in any case, the td?
}

Or is there a better way to label the field header, with my preferred display name in the first place? I guess I could just swap @Html.LabelFor... for Hard code field name but do I have to?

Upvotes: 0

Views: 293

Answers (2)

tvanfosson
tvanfosson

Reputation: 532465

It's inserting a label element, which should correspond to a valid input on the page. You can (a) either not worry about it, (b) output the text directly without using LabelFor, (c) write a custom helper that extracts the label text from the model without wrapping it in a label, or (d) unwrap it with javascript on the client (which will make it pass validation, but only after running the script).

Here's an extension based on the LabelFor code that should help with (c). Untested.

 public static class HelperExtensions
 {
      public static MvcHtmlString TableHeaderFor<TModel,TValue)( this HtmlHelper<TModel> html, Expression<Func<TModel,TValue>> expression )
      {
           var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
           string headerText = metadata.DisplayName ?? metadata.PropertyName ?? ExpressionHelper.GetExpressionText(expression);
           return new MvcHtmlString( headerText );
      }
}

Upvotes: 1

Paul Hennessey
Paul Hennessey

Reputation: 203

Is it just a case issue? Your line:

@Html.LabelFor(x => x.First().Weekstarting)

contains 'Weekstarting', whereas the actual property is called 'WeekStarting'.

Upvotes: 1

Related Questions