Last active
August 29, 2015 14:15
-
-
Save arielmoraes/6aaad289bf2d3ca1a48e to your computer and use it in GitHub Desktop.
Bootstrap ASP.NET MVC Switch
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
public static MvcHtmlString SwitchFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string trueString, string falseString) | |
{ | |
if (expression == null) | |
throw new ArgumentNullException("expression"); | |
var body = expression.Body as MemberExpression; | |
if (body == null) | |
throw new ArgumentNullException("expression"); | |
bool truthValue = (bool)ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model; | |
var wrapper = new TagBuilder("div"); | |
wrapper.AddCssClass("btn-group"); | |
wrapper.AddCssClass("btn-toggle"); | |
wrapper.Attributes.Add(new KeyValuePair<string, string>("data-toggle", "buttons")); | |
wrapper.InnerHtml += CreateSwitchInput(body.Member.Name, "true", trueString, truthValue); | |
wrapper.InnerHtml += CreateSwitchInput(body.Member.Name, "false", falseString, !truthValue); | |
return MvcHtmlString.Create(wrapper.ToString()); | |
} | |
private static string CreateSwitchInput(string name, string value, string text, bool selected) | |
{ | |
var label = new TagBuilder("label"); | |
label.AddCssClass("btn"); | |
if (selected) | |
{ | |
label.AddCssClass("btn-primary"); | |
label.AddCssClass("active"); | |
} | |
else | |
{ | |
label.AddCssClass("btn-default"); | |
} | |
var input = new TagBuilder("input"); | |
input.Attributes.Add(new KeyValuePair<string, string>("type", "radio")); | |
input.Attributes.Add(new KeyValuePair<string, string>("id", name)); | |
input.Attributes.Add(new KeyValuePair<string, string>("name", name)); | |
input.Attributes.Add(new KeyValuePair<string, string>("value", value)); | |
label.InnerHtml += input.ToString() + " " + text; | |
return label.ToString(); | |
} |
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
function bindToggleButton(selector) { | |
$(selector).click(function () { | |
$(this).find('.btn').toggleClass('active'); | |
if ($(this).find('.btn-primary').size() > 0) { | |
$(this).find('.btn').toggleClass('btn-primary'); | |
} | |
$(this).find('.btn').toggleClass('btn-default'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment