A web developer at work recently wanted to wrap a input tag inside a label tag for easier layout. The HTML wanted looked like this:
<label for="name">Name:<input type="text" id="name" name="name" /></label>
This was a in MVC project, and because of this I’ve decided to create an extension method to do this. The extension method should also support adding attributes to the label tag. The extension method I came up with looks like this:
1: public static string LabelWrap(this HtmlHelper helper, string label, MvcHtmlString @object, object attribtues = null)2: {3: StringBuilder sb = new StringBuilder();
4: Match match = Regex.Match(@object.ToHtmlString(), @"id=""(?<ID>\w+)""");5: if (match.Success)
6: {7: sb.AppendFormat(@"<label for=""{0}""", match.Groups["ID"].Value);8: if (attribtues != null)
9: {10: PropertyInfo[] propertyInfos = attribtues.GetType().GetProperties();
11: foreach (PropertyInfo propertyInfo in propertyInfos)
12: {13: sb.AppendFormat(@" {0}=""{1}""", propertyInfo.Name, propertyInfo.GetValue(attribtues, null));
14: }15: }16: sb.AppendFormat(">{0}{1}", label, @object.ToHtmlString());17: sb.Append("</label>");
18: }19: return sb.ToString();
20: }21: }
The method doesn’t take into account, whether or id could be found.
Using the method is very simple
@Html.LabelWrap("Name:", Html.TextBoxFor(model => model.Name))
And adding attributes to the label tag, just as easy
Could it be easier?@Html.LabelWrap("Name:", Html.TextBoxFor(model => model.Name), new { @class = "cssClass" })
No comments:
Post a Comment