0

How may I create a strongly-typed label with HTML content inside in MVC3?

<label for="nnn"><input type="checkbox" id="nnn" />Herp</label>

I have checked the code in the w3c validator and it seems to be valid, is there a way to do it?

Thanks.

vtortola
  • 34,709
  • 29
  • 161
  • 263

1 Answers1

2

You could use a custom HTML helper with TagBuilder.

Something like this (untested);

public static MvcHtmlString LabelCheckBoxFor<TModel>(
   this HtmlHelper<TModel> htmlHelper, 
   Expression<Func<TModel,bool>> expression,
   string text)
{
   var labelTag = new TagBuilder("label");
   labelTag.MergeAttribute("for", "nnn"); 
   labelTag.InnerHtml = htmlHelper.CheckBoxFor(expression) + text;
   return labelTag.ToString(TagRenderMode.SelfClosing);
}

Might not be 100% but you get the idea. I'm not sure how to pull the "for" value out of the model. You might need FromLambdaExpression, or another parameter.

And use it like this:

@Html.LabelCheckBoxFor(model => model.SomeField, "Herp")
RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • I see, that is pretty cool. Do you know how can I set the "value" attribute so I can set the value back where there are validation problems? Thanks. – vtortola Jul 21 '11 at 11:33
  • 2
    it works great, I changed the last line to MvcHtmlString.Create() But yes, your idea works great! Thanks a million. – vtortola Jul 21 '11 at 16:11