Created
November 22, 2013 16:54
-
-
Save cmillr/7603151 to your computer and use it in GitHub Desktop.
Provides a standard input control for forms on Bootstrap, along with inline validation messages and highlighting.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq.Expressions; | |
using System.Web.Mvc; | |
using System.Web.Mvc.Html; | |
public static class BootstrapHtmlHelper | |
{ | |
public static MvcHtmlString BootstrapInputFor<TModel, TProp>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProp>> expr, string name) | |
{ | |
var controlName = ExpressionHelper.GetExpressionText(expr); | |
var errorMessage = ""; | |
if (helper.ViewData.ModelState.ContainsKey(controlName)) | |
{ | |
var errors = helper.ViewData.ModelState[controlName].Errors; | |
if (errors != null && errors.Count > 0) errorMessage = errors[0].ErrorMessage; | |
} | |
var classes = "control-group"; | |
if (!string.IsNullOrWhiteSpace(errorMessage)) classes += " error"; | |
return new MvcHtmlString(string.Format(@" | |
<div class=""{0}""> | |
{1} | |
<div class=""controls""> | |
{2} | |
<span class=""help-inline"">{3}</span> | |
</div> | |
</div> | |
", | |
classes, | |
helper.LabelFor(expr, name, new Dictionary<string, object> {{"class","control-label"}}), | |
helper.TextBoxFor(expr), | |
errorMessage)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment