Skip to content

Instantly share code, notes, and snippets.

@multinerd
Created April 19, 2018 21:21
Show Gist options
  • Save multinerd/21debdc7a9278049c82ae8078e1b148b to your computer and use it in GitHub Desktop.
Save multinerd/21debdc7a9278049c82ae8078e1b148b to your computer and use it in GitHub Desktop.
public static class MvcHtmlHelpers
{
/// <summary>
/// Renders checkbox as one input (normal Html.CheckBoxFor renders two inputs: checkbox and hidden)
/// </summary>
public static MvcHtmlString BasicCheckBoxFor<T>(this HtmlHelper<T> html, Expression<Func<T, bool>> expression, object htmlAttributes = null)
{
var tag = new TagBuilder("input");
tag.Attributes["type"] = "checkbox";
tag.Attributes["id"] = html.IdFor(expression).ToString();
tag.Attributes["name"] = html.NameFor(expression).ToString();
tag.Attributes["value"] = "false";
// set the "checked" attribute if true
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
if (metadata.Model != null)
{
if (bool.TryParse(metadata.Model.ToString(), out var modelChecked))
{
if (modelChecked)
{
tag.Attributes["checked"] = "checked";
}
}
}
// merge custom attributes
tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), true);
var tagString = tag.ToString(TagRenderMode.SelfClosing);
return MvcHtmlString.Create(tagString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment