Skip to content

Instantly share code, notes, and snippets.

@danielmackay
Created March 9, 2014 05:19
Show Gist options
  • Save danielmackay/9443214 to your computer and use it in GitHub Desktop.
Save danielmackay/9443214 to your computer and use it in GitHub Desktop.
A collection of MVC HTML helpers for bootstrap alerts, buttons, pagingation, and more. #mvc, #bootstrap.
public static class HtmlHelpers
{
public static HtmlString BootstrapAlert(this HtmlHelper htmlHelper, string message, Enums.AlertType alertType)
{
return BootstrapAlert(htmlHelper, new List<string>() { message }, alertType); ;
}
public static HtmlString BootstrapAlert(this HtmlHelper htmlHelper, List<string> messages, Enums.AlertType alertType)
{
_BootstrapAlertModel model = new _BootstrapAlertModel() { Messages = messages };
switch (alertType)
{
case Enums.AlertType.Error:
model.CssClass = "alert-danger";
break;
case Enums.AlertType.Information:
model.CssClass = "alert-info";
break;
case Enums.AlertType.Success:
model.CssClass = "alert-success";
break;
case Enums.AlertType.Warning:
model.CssClass = "alert-warning";
break;
}
return PartialExtensions.Partial(htmlHelper, "_BootstrapAlert", model);
}
public static HtmlString BootstrapValidationSummary(this HtmlHelper htmlHelper)
{
if (!htmlHelper.ViewData.ModelState.IsValid)
{
List<string> messages = new List<string>();
foreach (ModelError modelError in htmlHelper.ViewData.ModelState.SelectMany(kvp => kvp.Value.Errors))
messages.Add(modelError.ErrorMessage);
return BootstrapAlert(htmlHelper, messages, Enums.AlertType.Error);
}
else
return null;
}
public static MvcHtmlString Button(this HtmlHelper htmlHelper, string text, Enums.ButtonType buttonType, Enums.ButtonStyle buttonStyle, Enums.IconType? iconType, Enums.ButtonSize? buttonSize = null, object htmlAttributes = null)
{
//<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-cog"></span>&nbsp;Generate Demand Plan</button>
TagBuilder button = new TagBuilder("button");
string iconHtml = string.Empty;
string buttonTypeString;
List<string> cssClasses = new List<string>() { "btn" };
switch (buttonType)
{
default:
case Enums.ButtonType.Button:
buttonTypeString = "button";
break;
case Enums.ButtonType.Reset:
buttonTypeString = "reset";
break;
case Enums.ButtonType.Submit:
buttonTypeString = "submit";
break;
}
switch (buttonStyle)
{
case Enums.ButtonStyle.Danger:
cssClasses.Add("btn-danger");
break;
case Enums.ButtonStyle.Default:
cssClasses.Add("btn-default");
break;
case Enums.ButtonStyle.Primary:
cssClasses.Add("btn-primary");
break;
case Enums.ButtonStyle.Success:
cssClasses.Add("btn-success");
break;
}
if (buttonSize != null)
{
switch (buttonSize.Value)
{
case Enums.ButtonSize.ExtraSmall:
cssClasses.Add("btn-xs");
break;
case Enums.ButtonSize.Small:
cssClasses.Add("btn-sm");
break;
case Enums.ButtonSize.Large:
cssClasses.Add("btn-lg");
break;
}
}
if (iconType != null)
{ //<span class="glyphicon glyphicon-cog"></span>&nbsp;
TagBuilder span = new TagBuilder("span");
string iconClass;
switch (iconType.Value)
{
case Enums.IconType.Add:
iconClass = "plus";
break;
case Enums.IconType.Generate:
iconClass = "cog";
break;
case Enums.IconType.Remove:
iconClass = "trash";
break;
case Enums.IconType.Search:
iconClass = "search";
break;
case Enums.IconType.Select:
iconClass = "check";
break;
default:
iconClass = string.Empty;
break;
}
span.MergeAttribute("class", "glyphicon glyphicon-" + iconClass);
iconHtml = span.ToString(TagRenderMode.Normal) + " ";
}
button.MergeAttribute("type", buttonTypeString);
button.MergeAttribute("class", string.Join(" ", cssClasses));
button.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
button.InnerHtml = iconHtml + WebUtility.HtmlEncode(text);
return MvcHtmlString.Create(button.ToString(TagRenderMode.Normal));
}
public static MvcHtmlString Button_Add(this HtmlHelper htmlHelper, string text, Enums.ButtonType buttonType, Enums.ButtonSize? buttonSize = null, object htmlAttributes = null)
{
return Button(htmlHelper, text, buttonType, Enums.ButtonStyle.Primary, Enums.IconType.Add, buttonSize, htmlAttributes);
}
public static MvcHtmlString Button_Cancel(this HtmlHelper htmlHelper, Enums.ButtonSize? buttonSize = null, object htmlAttributes = null)
{
return Button(htmlHelper, "Cancel", Enums.ButtonType.Button, Enums.ButtonStyle.Default, null, buttonSize, htmlAttributes);
}
public static MvcHtmlString Button_Clear(this HtmlHelper htmlHelper, Enums.ButtonSize? buttonSize = null, object htmlAttributes = null)
{
return Button(htmlHelper, "Clear", Enums.ButtonType.Reset, Enums.ButtonStyle.Default, null, buttonSize, htmlAttributes);
}
public static MvcHtmlString Button_Edit(this HtmlHelper htmlHelper, Enums.ButtonSize? buttonSize = null, object htmlAttributes = null)
{
return Button(htmlHelper, "Edit", Enums.ButtonType.Button, Enums.ButtonStyle.Primary, null, buttonSize, htmlAttributes);
}
public static MvcHtmlString Button_Generate(this HtmlHelper htmlHelper, string text, Enums.ButtonSize? buttonSize = null, object htmlAttributes = null)
{
return Button(htmlHelper, text, Enums.ButtonType.Submit, Enums.ButtonStyle.Primary, Enums.IconType.Generate, buttonSize, htmlAttributes);
}
public static MvcHtmlString Button_Remove(this HtmlHelper htmlHelper, Enums.ButtonSize? buttonSize = null, object htmlAttributes = null)
{
return Button(htmlHelper, null, Enums.ButtonType.Button, Enums.ButtonStyle.Danger, Enums.IconType.Remove, buttonSize, htmlAttributes);
}
public static MvcHtmlString Button_Save(this HtmlHelper htmlHelper, Enums.ButtonSize? buttonSize = null, object htmlAttributes = null)
{
return Button(htmlHelper, "Save", Enums.ButtonType.Submit, Enums.ButtonStyle.Primary, null, buttonSize, htmlAttributes);
}
public static MvcHtmlString Button_Search(this HtmlHelper htmlHelper, Enums.ButtonSize? buttonSize = null, object htmlAttributes = null)
{
return Button(htmlHelper, "Search", Enums.ButtonType.Submit, Enums.ButtonStyle.Primary, Enums.IconType.Search, buttonSize, htmlAttributes);
}
public static MvcHtmlString Button_Select(this HtmlHelper htmlHelper, Enums.ButtonSize? buttonSize = null, object htmlAttributes = null)
{
return Button(htmlHelper, "Select", Enums.ButtonType.Button, Enums.ButtonStyle.Success, Enums.IconType.Select, buttonSize, htmlAttributes);
}
public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> selectedValueField, List<SelectListItem> items, bool showSelectAll)
{
string fieldName = ExpressionHelper.GetExpressionText(selectedValueField);
string fullBindingName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldName);
_CheckBoxListModel model = new _CheckBoxListModel()
{
FieldName = fullBindingName,
ShowSelectAll = true,
Items = items
};
return PartialExtensions.Partial(htmlHelper, "_CheckBoxList", model);
}
public static MvcHtmlString DatePickerFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, DateTime?>> valueFieldExpression, Dictionary<string, object> htmlAttributes = null)
{
string fieldName = ExpressionHelper.GetExpressionText(valueFieldExpression);
string fullBindingName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldName);
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(valueFieldExpression, htmlHelper.ViewData);
DateTime? value = (DateTime?)metadata.Model;
_DatePickerModel model = new _DatePickerModel()
{
FieldName = fullBindingName,
Value = value,
HtmlAttributes = htmlAttributes ?? new Dictionary<string, object>()
};
if (!model.HtmlAttributes.ContainsKey("class"))
model.HtmlAttributes.Add("class", "form-control");
return PartialExtensions.Partial(htmlHelper, "_DatePicker", model);
}
public static MvcHtmlString HtmlLink(this HtmlHelper htmlHelper, string url, string text, object htmlAttributes = null)
{
TagBuilder tb = new TagBuilder("a");
tb.InnerHtml = WebUtility.HtmlEncode(text);
tb.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
tb.MergeAttribute("href", url);
return MvcHtmlString.Create(tb.ToString(TagRenderMode.Normal));
}
public static MvcHtmlString IDFieldFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
{
TagBuilder tb = new TagBuilder("input");
string fieldName = ExpressionHelper.GetExpressionText(expression);
string fullBindingName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldName);
string fieldId = TagBuilder.CreateSanitizedId(fullBindingName);
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
object value = metadata.Model;
tb.MergeAttribute("type", "hidden");
tb.MergeAttribute("id", fieldId);
tb.MergeAttribute("name", fullBindingName);
tb.MergeAttribute("value", value == null ? "" : value.ToString()); //always use value in model (i.e. by default value in post can override value in model)
tb.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
return MvcHtmlString.Create(tb.ToString(TagRenderMode.SelfClosing));
}
public static MvcHtmlString ImportInstructions(this HtmlHelper htmlHelper, _ImportInstructionsModel model)
{
return PartialExtensions.Partial(htmlHelper, "_ImportInstructions", model);
}
public static MvcHtmlString ImportRowSummary(this HtmlHelper htmlHelper, _ImportRowSummaryModel model)
{
return PartialExtensions.Partial(htmlHelper, "_ImportRowSummary", model);
}
public static MvcHtmlString ItemsDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> selectedItemIDField, List<_ItemsDropDownListModel.ItemCategoryModel> itemCategories, bool multiSelect, string placeholderText)
{
string fieldName = ExpressionHelper.GetExpressionText(selectedItemIDField);
string fullBindingName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldName);
return ItemsDropDownListFor(htmlHelper, fullBindingName, itemCategories, multiSelect, placeholderText);
}
public static MvcHtmlString ItemsDropDownListFor(this HtmlHelper htmlHelper, string selectedItemIDField, List<_ItemsDropDownListModel.ItemCategoryModel> itemCategories, bool multiSelect, string placeholderText)
{
_ItemsDropDownListModel model = new _ItemsDropDownListModel()
{
ItemIDFieldName = selectedItemIDField,
ItemCategories = itemCategories,
MultiSelect = multiSelect,
PlaceholderText = placeholderText
};
return PartialExtensions.Partial(htmlHelper, "_ItemsDropDownList", model);
}
public static MvcHtmlString MonthPickerFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, DateTime?>> valueFieldExpression, Dictionary<string, object> htmlAttributes = null)
{
string fieldName = ExpressionHelper.GetExpressionText(valueFieldExpression);
string fullBindingName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldName);
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(valueFieldExpression, htmlHelper.ViewData);
DateTime? value = (DateTime?)metadata.Model;
_MonthPickerModel model = new _MonthPickerModel()
{
FieldName = fullBindingName,
Value = value,
HtmlAttributes = htmlAttributes ?? new Dictionary<string, object>()
};
if (!model.HtmlAttributes.ContainsKey("class"))
model.HtmlAttributes.Add("class", "form-control");
return PartialExtensions.Partial(htmlHelper, "_MonthPicker", model);
}
public static MvcHtmlString PaginationFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, int startRow, int totalRows, int pageSize, bool showPageSize, Expression<Func<TModel, TProperty>> startRowFieldExpression, Expression<Func<TModel, TProperty>> pageSizeFieldExpression)
{
string startRowFieldName = ExpressionHelper.GetExpressionText(startRowFieldExpression);
string pageSizeFieldName = ExpressionHelper.GetExpressionText(pageSizeFieldExpression);
string startRowFullBindingName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(startRowFieldName);
string pageSizeFullBindingName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(pageSizeFieldName);
return PaginationFor(htmlHelper, startRow, totalRows, pageSize, showPageSize, startRowFullBindingName, pageSizeFullBindingName);
}
public static MvcHtmlString PaginationFor(this HtmlHelper htmlHelper, int startRow, int totalRows, int pageSize, bool showPageSize, string startRowFieldName, string pageSizeFieldName)
{
int totalPages = (int)Math.Ceiling((double)totalRows / pageSize);
int currentPage = ((startRow - 1) / pageSize) + 1;
_PaginationModel model = new _PaginationModel()
{
StartRowFieldName = startRowFieldName,
PageSizeFieldName = pageSizeFieldName,
CurrentPage = currentPage,
ShowPageSize = showPageSize,
Pages = new List<_PaginationModel.PageModel>(),
PageSizes = Enum.GetValues(typeof(Enums.PageSize))
.Cast<Enums.PageSize>()
.Select(ps => new SelectListItem()
{
Value = ((int)ps).ToString(),
Text = ((int)ps).ToString(),
Selected = (int)ps == pageSize
}).ToList()
};
if (totalPages <= 10)
{
for (int i = 1; i <= totalPages; i++)
model.Pages.Add(GetPaginationFor_PageModel(i, pageSize));
}
else
{ //render the pagination control, e.g. < 1 2 3 4 5 ... 57 58 [59] 60 61 .... 950 951 >
const int MIN_NUMBER_OF_PAGES_TO_SHOW_AT_START = 5;
const int MIN_NUMBER_OF_PAGES_TO_SHOW_AT_END = 2;
const int MIN_NUMBER_OF_PAGES_TO_SHOW_EITHER_SIDE_OF_CURRENT_PAGE = 2;
//add first 5 pages
for (int i = 1; i <= MIN_NUMBER_OF_PAGES_TO_SHOW_AT_START && i <= totalPages; i++)
model.Pages.Add(GetPaginationFor_PageModel(i, pageSize));
//add ...
if (currentPage - MIN_NUMBER_OF_PAGES_TO_SHOW_EITHER_SIDE_OF_CURRENT_PAGE > MIN_NUMBER_OF_PAGES_TO_SHOW_AT_START + 2)
model.Pages.Add(GetPaginationFor_PageModel(null, pageSize));
else if (currentPage - MIN_NUMBER_OF_PAGES_TO_SHOW_EITHER_SIDE_OF_CURRENT_PAGE == MIN_NUMBER_OF_PAGES_TO_SHOW_AT_START + 2)
model.Pages.Add(GetPaginationFor_PageModel(MIN_NUMBER_OF_PAGES_TO_SHOW_AT_START + 1, pageSize));
//add the 2 pages before the current page, the current page, and the 2 pages after the current page
for (int i = Math.Max(currentPage - MIN_NUMBER_OF_PAGES_TO_SHOW_EITHER_SIDE_OF_CURRENT_PAGE, MIN_NUMBER_OF_PAGES_TO_SHOW_AT_START + 1); i <= currentPage + MIN_NUMBER_OF_PAGES_TO_SHOW_EITHER_SIDE_OF_CURRENT_PAGE && i <= totalPages; i++)
model.Pages.Add(GetPaginationFor_PageModel(i, pageSize));
//add ...
if (currentPage + MIN_NUMBER_OF_PAGES_TO_SHOW_EITHER_SIDE_OF_CURRENT_PAGE < totalPages - MIN_NUMBER_OF_PAGES_TO_SHOW_AT_END - 1)
model.Pages.Add(GetPaginationFor_PageModel(null, pageSize));
else if (currentPage + MIN_NUMBER_OF_PAGES_TO_SHOW_EITHER_SIDE_OF_CURRENT_PAGE == totalPages - MIN_NUMBER_OF_PAGES_TO_SHOW_AT_END - 1)
model.Pages.Add(GetPaginationFor_PageModel(totalPages - MIN_NUMBER_OF_PAGES_TO_SHOW_AT_END, pageSize));
//add last 2 pages
for (int i = Math.Max(totalPages - MIN_NUMBER_OF_PAGES_TO_SHOW_AT_END + 1, currentPage + MIN_NUMBER_OF_PAGES_TO_SHOW_EITHER_SIDE_OF_CURRENT_PAGE + 1); i <= totalPages; i++)
model.Pages.Add(GetPaginationFor_PageModel(i, pageSize));
}
return PartialExtensions.Partial(htmlHelper, "_Pagination", model);
}
private static _PaginationModel.PageModel GetPaginationFor_PageModel(int? pageNumber, int pageSize)
{
return new _PaginationModel.PageModel()
{
Text = pageNumber.HasValue ? pageNumber.Value.ToString() : "...",
PageNumber = pageNumber,
StartRow = pageNumber.HasValue ? (pageSize * (pageNumber.Value - 1)) + 1 : (int?)null
};
}
}
@ascariz
Copy link

ascariz commented Jan 7, 2016

Hey there
It gives compilation errors, as in:
Bootstrap Model Alert
_ItemsDropDownListModel
_PaginationModel
PageSize
_MonthPickerModel
Why is that? How do I fix this?

@muhlisatac
Copy link

Can you also share partial views with us like "_CheckBoxList","_DatePicker","_ItemsDropDownList","_Pagination"...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment