public
Created

Custom MVC Html extension. Wraps a LabelFor, EditorFor, and ValidationMessageFor for a property in a div. Saves a considerable amount of typing in Views. Also checks if the property has the Required attribute and adds a class to the label. Can pass in Html attributes which get applied to the containing div. This gives you hooks for styling and layout of form elements (the included CSS file shows a rudimentary example).

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
namespace System.Web.Mvc
{
public static class MyEditorForExtensions
{
public static MvcHtmlString MyEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return MyEditorForInternal(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(null));
}
 
public static MvcHtmlString MyEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return MyEditorForInternal(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
 
private static MvcHtmlString MyEditorForInternal<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
TagBuilder builder = new TagBuilder("div");
builder.MergeAttributes(htmlAttributes);
 
string labelHtml;
 
var test = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
if (test.IsRequired)
{
labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression, new { @class = "required" }).ToHtmlString();
}
else
{
labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString();
}
 
string editorHtml = Html.EditorExtensions.EditorFor(htmlHelper, expression).ToHtmlString();
string validationHtml = Html.ValidationExtensions.ValidationMessageFor(htmlHelper, expression).ToHtmlString();
builder.InnerHtml = labelHtml + editorHtml + validationHtml;
 
return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
}
}
}
gistfile2.css
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
fieldset {border:1px #ccc dotted; padding:0% 1%; margin:10px -10px;}
legend {font-weight:bold; font-size:123%; padding:0px 3px; margin-left:-3px; background-color:White;}
 
form div{float:left; margin:2% 3%;}
form div.oneSixth {width:10.4%;}
form div.oneThird {width:26.7%;}
form div.twoThirds {width:59.5%;}
form div.half {width:43%;}
form div.oneFourth{width:18.5%;}
 
label {display:block; margin-bottom:1px; width:auto; text-align:left;}
.required:after {content:url(images/icon_required.gif);}
 
form div.inline {margin:1% 3%;}
form div.inline input {width:60%; border:1px solid #ccc; text-align:left;}
form div.inline label {display:inline-block; width:30%; text-align:right; padding-right:12px;}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.