mvc给html扩展方法:

mvc给html扩展方法:

注意:扩展方法和所在的类都必须是 public static
如果在页面直接使用新扩展的方法,需要web.config里把Web.Helper名称命名空间加上,页面才能访问到
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
<add namespace="Web.Helper" />
</namespaces>
namespace MyHtmlExtension
{
public static class HtmlExtensions
{
#region Admin area extensions

public static MvcHtmlString Hint(this HtmlHelper helper, string value)
{
// Create tag builder
var builder = new TagBuilder("img");

// Add attributes
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
var url = MvcHtmlString.Create(urlHelper.Content("~/Administration/Content/images/ico-help.gif")).ToHtmlString();

builder.MergeAttribute("src", url);
builder.MergeAttribute("alt", value);
builder.MergeAttribute("title", value);

// Render tag
return MvcHtmlString.Create(builder.ToString());
}

public static HelperResult LocalizedEditor<T, TLocalizedModelLocal>(this HtmlHelper<T> helper, string name,
Func<int, HelperResult> localizedTemplate,
Func<T, HelperResult> standardTemplate)
where T : ILocalizedModel<TLocalizedModelLocal>
where TLocalizedModelLocal : ILocalizedModelLocal
{
return new HelperResult(writer =>
{
if (helper.ViewData.Model.Locales.Count > 1)
{
var tabStrip = new StringBuilder();
tabStrip.AppendLine(string.Format("<div id='{0}'>", name));
tabStrip.AppendLine("<ul>");

//default tab
tabStrip.AppendLine("<li class='k-state-active'>");
tabStrip.AppendLine("Standard");
tabStrip.AppendLine("</li>");

for (int i = 0; i < helper.ViewData.Model.Locales.Count; i++)
{
//languages
var locale = helper.ViewData.Model.Locales[i];
var language = EngineContext.Current.Resolve<ILanguageService>().GetLanguageById(locale.LanguageId);

tabStrip.AppendLine("<li>");
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
var iconUrl = urlHelper.Content("~/Content/images/flags/" + language.FlagImageFileName);
tabStrip.AppendLine(string.Format("<img class='k-image' alt='' src='{0}'>", iconUrl));
tabStrip.AppendLine(HttpUtility.HtmlEncode(language.Name));
tabStrip.AppendLine("</li>");
}
tabStrip.AppendLine("</ul>");

//default tab
tabStrip.AppendLine("<div>");
tabStrip.AppendLine(standardTemplate(helper.ViewData.Model).ToHtmlString());
tabStrip.AppendLine("</div>");

for (int i = 0; i < helper.ViewData.Model.Locales.Count; i++)
{
//languages
tabStrip.AppendLine("<div>");
tabStrip.AppendLine(localizedTemplate(i).ToHtmlString());
tabStrip.AppendLine("</div>");
}
tabStrip.AppendLine("</div>");
tabStrip.AppendLine("<script>");
tabStrip.AppendLine("$(document).ready(function() {");
tabStrip.AppendLine(string.Format("$('#{0}').kendoTabStrip(", name));
tabStrip.AppendLine("{");
tabStrip.AppendLine("animation: {");
tabStrip.AppendLine("open: {");
tabStrip.AppendLine("effects: "fadeIn"");
tabStrip.AppendLine("}");
tabStrip.AppendLine("}");
tabStrip.AppendLine("});");
tabStrip.AppendLine("});");
tabStrip.AppendLine("</script>");
writer.Write(new MvcHtmlString(tabStrip.ToString()));
}
else
{
standardTemplate(helper.ViewData.Model).WriteTo(writer);
}
});
}

public static MvcHtmlString DeleteConfirmation<T>(this HtmlHelper<T> helper, string buttonsSelector) where T : BaseYipongEntityModel
{
return DeleteConfirmation<T>(helper, "", buttonsSelector);
}

public static MvcHtmlString DeleteConfirmation<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipongEntityModel
{
if (String.IsNullOrEmpty(actionName))
actionName = "Delete";

var modalId = MvcHtmlString.Create(helper.ViewData.ModelMetadata.ModelType.Name.ToLower() + "-delete-confirmation")
.ToHtmlString();

var deleteConfirmationModel = new DeleteConfirmationModel
{
Id = helper.ViewData.Model.Id,
ControllerName = helper.ViewContext.RouteData.GetRequiredString("controller"),
ActionName = actionName,
WindowId = modalId
};

var window = new StringBuilder();
window.AppendLine(string.Format("<div id='{0}' style='display:none;'>", modalId));
window.AppendLine(helper.Partial("Delete", deleteConfirmationModel).ToHtmlString());
window.AppendLine("</div>");
window.AppendLine("<script>");
window.AppendLine("$(document).ready(function() {");
window.AppendLine(string.Format("$('#{0}').click(function (e) ", buttonsSelector));
window.AppendLine("{");
window.AppendLine("e.preventDefault();");
window.AppendLine(string.Format("var window = $('#{0}');", modalId));
window.AppendLine("if (!window.data('kendoWindow')) {");
window.AppendLine("window.kendoWindow({");
window.AppendLine("modal: true,");
window.AppendLine(string.Format("title: '{0}',", EngineContext.Current.Resolve<ILocalizationService>().GetResource("Common.AreYouSure")));
window.AppendLine("actions: ['Close']");
window.AppendLine("});");
window.AppendLine("}");
window.AppendLine("window.data('kendoWindow').center().open();");
window.AppendLine("});");
window.AppendLine("});");
window.AppendLine("</script>");

return MvcHtmlString.Create(window.ToString());
}


public static MvcHtmlString DeleteBrandCateConfirmation<T>(this HtmlHelper<T> helper, string buttonsSelector) where T : BaseYipongEntityModel
{
return DeleteBrandCateConfirmation<T>(helper, "", buttonsSelector);
}

public static MvcHtmlString DeleteBrandCateConfirmation<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipongEntityModel
{
if (String.IsNullOrEmpty(actionName))
actionName = "BrandCategoryDelete";

var modalId = MvcHtmlString.Create(helper.ViewData.ModelMetadata.ModelType.Name.ToLower() + "-delete-confirmation")
.ToHtmlString();

var deleteConfirmationModel = new DeleteConfirmationModel
{
Id = helper.ViewData.Model.Id,
ControllerName = helper.ViewContext.RouteData.GetRequiredString("controller"),
ActionName = actionName,
WindowId = modalId
};

var window = new StringBuilder();
window.AppendLine(string.Format("<div id='{0}' style='display:none;'>", modalId));
window.AppendLine(helper.Partial("Delete", deleteConfirmationModel).ToHtmlString());
window.AppendLine("</div>");
window.AppendLine("<script>");
window.AppendLine("$(document).ready(function() {");
window.AppendLine(string.Format("$('#{0}').click(function (e) ", buttonsSelector));
window.AppendLine("{");
window.AppendLine("e.preventDefault();");
window.AppendLine(string.Format("var window = $('#{0}');", modalId));
window.AppendLine("if (!window.data('kendoWindow')) {");
window.AppendLine("window.kendoWindow({");
window.AppendLine("modal: true,");
window.AppendLine(string.Format("title: '{0}',", EngineContext.Current.Resolve<ILocalizationService>().GetResource("Common.AreYouSure")));
window.AppendLine("actions: ['Close']");
window.AppendLine("});");
window.AppendLine("}");
window.AppendLine("window.data('kendoWindow').center().open();");
window.AppendLine("});");
window.AppendLine("});");
window.AppendLine("</script>");

return MvcHtmlString.Create(window.ToString());
}

public static MvcHtmlString DeleteConfirmationInfo<T>(this HtmlHelper<T> helper, string buttonsSelector) where T : BaseYipongEntityModel
{
return DeleteConfirmationInfo<T>(helper, "", buttonsSelector);
}

public static MvcHtmlString DeleteConfirmationInfo<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipongEntityModel
{
if (String.IsNullOrEmpty(actionName))
actionName = "CostDelete";

var modalId = MvcHtmlString.Create(helper.ViewData.ModelMetadata.ModelType.Name.ToLower() + "-delete-confirmation")
.ToHtmlString();

var deleteConfirmationModel = new DeleteConfirmationModel
{
Id = helper.ViewData.Model.Id,
ControllerName = helper.ViewContext.RouteData.GetRequiredString("controller"),
ActionName = actionName,
WindowId = modalId
};

var window = new StringBuilder();
window.AppendLine(string.Format("<div id='{0}' style='display:none;'>", modalId));
window.AppendLine(helper.Partial("Delete", deleteConfirmationModel).ToHtmlString());
window.AppendLine("</div>");
window.AppendLine("<script>");
window.AppendLine("$(document).ready(function() {");
window.AppendLine(string.Format("$('#{0}').click(function (e) ", buttonsSelector));
window.AppendLine("{");
window.AppendLine("e.preventDefault();");
window.AppendLine(string.Format("var window = $('#{0}');", modalId));
window.AppendLine("if (!window.data('kendoWindow')) {");
window.AppendLine("window.kendoWindow({");
window.AppendLine("modal: true,");
window.AppendLine(string.Format("title: '{0}',", EngineContext.Current.Resolve<ILocalizationService>().GetResource("Common.AreYouSure")));
window.AppendLine("actions: ['Close']");
window.AppendLine("});");
window.AppendLine("}");
window.AppendLine("window.data('kendoWindow').center().open();");
window.AppendLine("});");
window.AppendLine("});");
window.AppendLine("</script>");

return MvcHtmlString.Create(window.ToString());
}


public static MvcHtmlString DeleteConfirmationJLInfo<T>(this HtmlHelper<T> helper, string buttonsSelector) where T : BaseYipongEntityModel
{
return DeleteConfirmationJLInfo<T>(helper, "", buttonsSelector);
}

public static MvcHtmlString DeleteConfirmationJLInfo<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipongEntityModel
{
if (String.IsNullOrEmpty(actionName))
actionName = "JLCostDelete";

var modalId = MvcHtmlString.Create(helper.ViewData.ModelMetadata.ModelType.Name.ToLower() + "-delete-confirmation")
.ToHtmlString();

var deleteConfirmationModel = new DeleteConfirmationModel
{
Id = helper.ViewData.Model.Id,
ControllerName = helper.ViewContext.RouteData.GetRequiredString("controller"),
ActionName = actionName,
WindowId = modalId
};

var window = new StringBuilder();
window.AppendLine(string.Format("<div id='{0}' style='display:none;'>", modalId));
window.AppendLine(helper.Partial("Delete", deleteConfirmationModel).ToHtmlString());
window.AppendLine("</div>");
window.AppendLine("<script>");
window.AppendLine("$(document).ready(function() {");
window.AppendLine(string.Format("$('#{0}').click(function (e) ", buttonsSelector));
window.AppendLine("{");
window.AppendLine("e.preventDefault();");
window.AppendLine(string.Format("var window = $('#{0}');", modalId));
window.AppendLine("if (!window.data('kendoWindow')) {");
window.AppendLine("window.kendoWindow({");
window.AppendLine("modal: true,");
window.AppendLine(string.Format("title: '{0}',", EngineContext.Current.Resolve<ILocalizationService>().GetResource("Common.AreYouSure")));
window.AppendLine("actions: ['Close']");
window.AppendLine("});");
window.AppendLine("}");
window.AppendLine("window.data('kendoWindow').center().open();");
window.AppendLine("});");
window.AppendLine("});");
window.AppendLine("</script>");

return MvcHtmlString.Create(window.ToString());
}


public static MvcHtmlString DeleteConfirmationSellerInfo<T>(this HtmlHelper<T> helper, string buttonsSelector) where T : BaseYipongEntityModel
{
return DeleteConfirmationSellerInfo<T>(helper, "", buttonsSelector);
}

public static MvcHtmlString DeleteConfirmationSellerInfo<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipongEntityModel
{
if (String.IsNullOrEmpty(actionName))
actionName = "SellerCostDelete";

var modalId = MvcHtmlString.Create(helper.ViewData.ModelMetadata.ModelType.Name.ToLower() + "-delete-confirmation")
.ToHtmlString();

var deleteConfirmationModel = new DeleteConfirmationModel
{
Id = helper.ViewData.Model.Id,
ControllerName = helper.ViewContext.RouteData.GetRequiredString("controller"),
ActionName = actionName,
WindowId = modalId
};

var window = new StringBuilder();
window.AppendLine(string.Format("<div id='{0}' style='display:none;'>", modalId));
window.AppendLine(helper.Partial("Delete", deleteConfirmationModel).ToHtmlString());
window.AppendLine("</div>");
window.AppendLine("<script>");
window.AppendLine("$(document).ready(function() {");
window.AppendLine(string.Format("$('#{0}').click(function (e) ", buttonsSelector));
window.AppendLine("{");
window.AppendLine("e.preventDefault();");
window.AppendLine(string.Format("var window = $('#{0}');", modalId));
window.AppendLine("if (!window.data('kendoWindow')) {");
window.AppendLine("window.kendoWindow({");
window.AppendLine("modal: true,");
window.AppendLine(string.Format("title: '{0}',", EngineContext.Current.Resolve<ILocalizationService>().GetResource("Common.AreYouSure")));
window.AppendLine("actions: ['Close']");
window.AppendLine("});");
window.AppendLine("}");
window.AppendLine("window.data('kendoWindow').center().open();");
window.AppendLine("});");
window.AppendLine("});");
window.AppendLine("</script>");

return MvcHtmlString.Create(window.ToString());
}


public static MvcHtmlString DeleteConfirmationStoreInfo<T>(this HtmlHelper<T> helper, string buttonsSelector) where T : BaseYipongEntityModel
{
return DeleteConfirmationStoreInfo<T>(helper, "", buttonsSelector);
}

public static MvcHtmlString DeleteConfirmationStoreInfo<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipongEntityModel
{
if (String.IsNullOrEmpty(actionName))
actionName = "StoreCostDelete";

var modalId = MvcHtmlString.Create(helper.ViewData.ModelMetadata.ModelType.Name.ToLower() + "-delete-confirmation")
.ToHtmlString();

var deleteConfirmationModel = new DeleteConfirmationModel
{
Id = helper.ViewData.Model.Id,
ControllerName = helper.ViewContext.RouteData.GetRequiredString("controller"),
ActionName = actionName,
WindowId = modalId
};

var window = new StringBuilder();
window.AppendLine(string.Format("<div id='{0}' style='display:none;'>", modalId));
window.AppendLine(helper.Partial("Delete", deleteConfirmationModel).ToHtmlString());
window.AppendLine("</div>");
window.AppendLine("<script>");
window.AppendLine("$(document).ready(function() {");
window.AppendLine(string.Format("$('#{0}').click(function (e) ", buttonsSelector));
window.AppendLine("{");
window.AppendLine("e.preventDefault();");
window.AppendLine(string.Format("var window = $('#{0}');", modalId));
window.AppendLine("if (!window.data('kendoWindow')) {");
window.AppendLine("window.kendoWindow({");
window.AppendLine("modal: true,");
window.AppendLine(string.Format("title: '{0}',", EngineContext.Current.Resolve<ILocalizationService>().GetResource("Common.AreYouSure")));
window.AppendLine("actions: ['Close']");
window.AppendLine("});");
window.AppendLine("}");
window.AppendLine("window.data('kendoWindow').center().open();");
window.AppendLine("});");
window.AppendLine("});");
window.AppendLine("</script>");

return MvcHtmlString.Create(window.ToString());
}

public static MvcHtmlString YipongLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, bool displayHint = true)
{
var result = new StringBuilder();
var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
var hintResource = string.Empty;
object value = null;
if (metadata.AdditionalValues.TryGetValue("YipongResourceDisplayName", out value))
{
var resourceDisplayName = value as YipongResourceDisplayName;
if (resourceDisplayName != null && displayHint)
{
var langId = EngineContext.Current.Resolve<IWorkContext>().WorkingLanguage.Id;
hintResource =
EngineContext.Current.Resolve<ILocalizationService>()
.GetResource(resourceDisplayName.ResourceKey + ".Hint", langId);

result.Append(helper.Hint(hintResource).ToHtmlString());
}
}
result.Append(helper.LabelFor(expression, new { title = hintResource }));
return MvcHtmlString.Create(result.ToString());
}

public static MvcHtmlString OverrideStoreCheckboxFor<TModel, TValue>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, bool>> expression,
Expression<Func<TModel, TValue>> forInputExpression,
int activeStoreScopeConfiguration)
{
var dataInputIds = new List<string>();
dataInputIds.Add(helper.FieldIdFor(forInputExpression));
return OverrideStoreCheckboxFor(helper, expression, activeStoreScopeConfiguration, null, dataInputIds.ToArray());
}
public static MvcHtmlString OverrideStoreCheckboxFor<TModel, TValue1, TValue2>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, bool>> expression,
Expression<Func<TModel, TValue1>> forInputExpression1,
Expression<Func<TModel, TValue2>> forInputExpression2,
int activeStoreScopeConfiguration)
{
var dataInputIds = new List<string>();
dataInputIds.Add(helper.FieldIdFor(forInputExpression1));
dataInputIds.Add(helper.FieldIdFor(forInputExpression2));
return OverrideStoreCheckboxFor(helper, expression, activeStoreScopeConfiguration, null, dataInputIds.ToArray());
}
public static MvcHtmlString OverrideStoreCheckboxFor<TModel, TValue1, TValue2, TValue3>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, bool>> expression,
Expression<Func<TModel, TValue1>> forInputExpression1,
Expression<Func<TModel, TValue2>> forInputExpression2,
Expression<Func<TModel, TValue3>> forInputExpression3,
int activeStoreScopeConfiguration)
{
var dataInputIds = new List<string>();
dataInputIds.Add(helper.FieldIdFor(forInputExpression1));
dataInputIds.Add(helper.FieldIdFor(forInputExpression2));
dataInputIds.Add(helper.FieldIdFor(forInputExpression3));
return OverrideStoreCheckboxFor(helper, expression, activeStoreScopeConfiguration, null, dataInputIds.ToArray());
}
public static MvcHtmlString OverrideStoreCheckboxFor<TModel>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, bool>> expression,
string parentContainer,
int activeStoreScopeConfiguration)
{
return OverrideStoreCheckboxFor(helper, expression, activeStoreScopeConfiguration, parentContainer);
}
private static MvcHtmlString OverrideStoreCheckboxFor<TModel>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, bool>> expression,
int activeStoreScopeConfiguration,
string parentContainer = null,
params string[] datainputIds)
{
if (String.IsNullOrEmpty(parentContainer) && datainputIds == null)
throw new ArgumentException("Specify at least one selector");

var result = new StringBuilder();
if (activeStoreScopeConfiguration > 0)
{
//render only when a certain store is chosen
const string cssClass = "multi-store-override-option";
string dataInputSelector = "";
if (!String.IsNullOrEmpty(parentContainer))
{
dataInputSelector = "#" + parentContainer + " input, #" + parentContainer + " textarea, #" + parentContainer + " select";
}
if (datainputIds != null && datainputIds.Length > 0)
{
dataInputSelector = "#" + String.Join(", #", datainputIds);
}
var onClick = string.Format("checkOverridenStoreValue(this, '{0}')", dataInputSelector);
result.Append(helper.CheckBoxFor(expression, new Dictionary<string, object>
{
{ "class", cssClass },
{ "onclick", onClick },
{ "data-for-input-selector", dataInputSelector },
}));
}
return MvcHtmlString.Create(result.ToString());
}

/// <summary>
/// Render CSS styles of selected index
/// </summary>
/// <param name="helper">HTML helper</param>
/// <param name="currentIndex">Current tab index (where appropriate CSS style should be rendred)</param>
/// <param name="indexToSelect">Tab index to select</param>
/// <returns>MvcHtmlString</returns>
public static MvcHtmlString RenderSelectedTabIndex(this HtmlHelper helper, int currentIndex, int indexToSelect)
{
if (helper == null)
throw new ArgumentNullException("helper");

//ensure it's not negative
if (indexToSelect < 0)
indexToSelect = 0;

//required validation
if (indexToSelect == currentIndex)
{
return new MvcHtmlString(" class='k-state-active'");
}

return new MvcHtmlString("");
}

#endregion

#region Common extensions

public static MvcHtmlString RequiredHint(this HtmlHelper helper, string additionalText = null)
{
// Create tag builder
var builder = new TagBuilder("span");
builder.AddCssClass("required");
var innerText = "*";
//add additional text if specified
if (!String.IsNullOrEmpty(additionalText))
innerText += " " + additionalText;
builder.SetInnerText(innerText);
// Render tag
return MvcHtmlString.Create(builder.ToString());
}

public static string FieldNameFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
{
return html.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
}
public static string FieldIdFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
{
var id = html.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
// because "[" and "]" aren't replaced with "_" in GetFullHtmlFieldId
return id.Replace('[', '_').Replace(']', '_');
}
/// <summary>
/// Creates a days, months, years drop down list using an HTML select control.
/// The parameters represent the value of the "name" attribute on the select control.
/// </summary>
/// <param name="html">HTML helper</param>
/// <param name="dayName">"Name" attribute of the day drop down list.</param>
/// <param name="monthName">"Name" attribute of the month drop down list.</param>
/// <param name="yearName">"Name" attribute of the year drop down list.</param>
/// <param name="beginYear">Begin year</param>
/// <param name="endYear">End year</param>
/// <param name="selectedDay">Selected day</param>
/// <param name="selectedMonth">Selected month</param>
/// <param name="selectedYear">Selected year</param>
/// <param name="localizeLabels">Localize labels</param>
/// <returns></returns>
public static MvcHtmlString DatePickerDropDownsTaiWan(this HtmlHelper html,
string dayName, string monthName, string yearName,
int? beginYear = null, int? endYear = null,
int? selectedDay = null, int? selectedMonth = null, int? selectedYear = null, bool localizeLabels = true)
{
var daysList = new TagBuilder("select");
var monthsList = new TagBuilder("select");
var yearsList = new TagBuilder("select");

var daysListName = new TagBuilder("label");
var monthsListName = new TagBuilder("label");
var yearsListName = new TagBuilder("label");


daysList.Attributes.Add("name", dayName);
monthsList.Attributes.Add("name", monthName);
yearsList.Attributes.Add("name", yearName);

var days = new StringBuilder();
var months = new StringBuilder();
var years = new StringBuilder();

string dayLocale, monthLocale, yearLocale;
if (localizeLabels)
{
var locService = EngineContext.Current.Resolve<ILocalizationService>();
dayLocale = locService.GetResource("Yipong.Info.Fileds.Day");
monthLocale = locService.GetResource("Yipong.Info.Fileds.Month");
yearLocale = locService.GetResource("Yipong.Info.Fileds.Year");
}
else
{
dayLocale = "Day";
monthLocale = "Month";
yearLocale = "Year";
}

days.AppendFormat("<option value='{0}'>{1}</option>", "0", "");
for (int i = 1; i <= 31; i++)
days.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
(selectedDay.HasValue && selectedDay.Value == i) ? " selected="selected"" : null);


months.AppendFormat("<option value='{0}'>{1}</option>", "0", "");
for (int i = 1; i <= 12; i++)
{
months.AppendFormat("<option value='{0}'{1}>{2}</option>",
i,
(selectedMonth.HasValue && selectedMonth.Value == i) ? " selected="selected"" : null,i);
}


years.AppendFormat("<option value='{0}'>{1}</option>", "0", "");

if (beginYear == null)
beginYear = CommonHelper.GetDateTimeNow().Year - 100;
if (endYear == null)
endYear = CommonHelper.GetDateTimeNow().Year;

if (endYear > beginYear)
{
for (int i = beginYear.Value; i <= endYear.Value; i++)
years.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
(selectedYear.HasValue && selectedYear.Value == i) ? " selected="selected"" : null);
}
else
{
for (int i = beginYear.Value; i >= endYear.Value; i--)
years.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
(selectedYear.HasValue && selectedYear.Value == i) ? " selected="selected"" : null);
}

daysList.InnerHtml = days.ToString();
monthsList.InnerHtml = months.ToString();
yearsList.InnerHtml = years.ToString();

daysListName.InnerHtml =dayLocale;
monthsListName.InnerHtml =monthLocale ;
yearsListName.InnerHtml = yearLocale;
return MvcHtmlString.Create(string.Concat(yearsList, yearLocale, monthsList, monthLocale, daysList, daysListName));
}
/// <summary>
/// Creates a days, months, years drop down list using an HTML select control.
/// The parameters represent the value of the "name" attribute on the select control.
/// </summary>
/// <param name="html">HTML helper</param>
/// <param name="dayName">"Name" attribute of the day drop down list.</param>
/// <param name="monthName">"Name" attribute of the month drop down list.</param>
/// <param name="yearName">"Name" attribute of the year drop down list.</param>
/// <param name="beginYear">Begin year</param>
/// <param name="endYear">End year</param>
/// <param name="selectedDay">Selected day</param>
/// <param name="selectedMonth">Selected month</param>
/// <param name="selectedYear">Selected year</param>
/// <param name="localizeLabels">Localize labels</param>
/// <returns></returns>
public static MvcHtmlString DatePickerDropDowns(this HtmlHelper html,
string dayName, string monthName, string yearName,
int? beginYear = null, int? endYear = null,
int? selectedDay = null, int? selectedMonth = null, int? selectedYear = null, bool localizeLabels = true)
{
var daysList = new TagBuilder("select");
var monthsList = new TagBuilder("select");
var yearsList = new TagBuilder("select");

daysList.Attributes.Add("name", dayName);
daysList.Attributes.Add("style", "80px;");
monthsList.Attributes.Add("name", monthName);
monthsList.Attributes.Add("style", "80px;");
yearsList.Attributes.Add("name", yearName);
yearsList.Attributes.Add("style", "80px;");

var days = new StringBuilder();
var months = new StringBuilder();
var years = new StringBuilder();

string dayLocale, monthLocale, yearLocale;
if (localizeLabels)
{
var locService = EngineContext.Current.Resolve<ILocalizationService>();
dayLocale = locService.GetResource("Common.Day");
monthLocale = locService.GetResource("Common.Month");
yearLocale = locService.GetResource("Common.Year");
}
else
{
dayLocale = "Day";
monthLocale = "Month";
yearLocale = "Year";
}

days.AppendFormat("<option value='{0}'>{1}</option>", "0", dayLocale);
for (int i = 1; i <= 31; i++)
days.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
(selectedDay.HasValue && selectedDay.Value == i) ? " selected="selected"" : null);


months.AppendFormat("<option value='{0}'>{1}</option>", "0", monthLocale);
for (int i = 1; i <= 12; i++)
{
months.AppendFormat("<option value='{0}'{1}>{2}</option>",
i,
(selectedMonth.HasValue && selectedMonth.Value == i) ? " selected="selected"" : null,
CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(i).TrimEnd());
}


years.AppendFormat("<option value='{0}'>{1}</option>", "0", yearLocale);

if (beginYear == null)
beginYear = CommonHelper.GetDateTimeNow().Year - 100;
if (endYear == null)
endYear = CommonHelper.GetDateTimeNow().Year;

if (endYear > beginYear)
{
for (int i = beginYear.Value; i <= endYear.Value; i++)
years.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
(selectedYear.HasValue && selectedYear.Value == i) ? " selected="selected"" : null);
}
else
{
for (int i = beginYear.Value; i >= endYear.Value; i--)
years.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
(selectedYear.HasValue && selectedYear.Value == i) ? " selected="selected"" : null);
}

daysList.InnerHtml = days.ToString();
monthsList.InnerHtml = months.ToString();
yearsList.InnerHtml = years.ToString();

return MvcHtmlString.Create(string.Concat(yearsList, monthsList, daysList));
}

public static MvcHtmlString Widget(this HtmlHelper helper, string widgetZone, object additionalData = null)
{
return helper.Action("WidgetsByZone", "Widget", new { widgetZone = widgetZone, additionalData = additionalData });
}

/// <summary>
/// Renders the standard label with a specified suffix added to label text
/// </summary>
/// <typeparam name="TModel">Model</typeparam>
/// <typeparam name="TValue">Value</typeparam>
/// <param name="html">HTML helper</param>
/// <param name="expression">Expression</param>
/// <param name="htmlAttributes">HTML attributes</param>
/// <param name="suffix">Suffix</param>
/// <returns>Label</returns>
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes, string suffix)
{
string htmlFieldName = ExpressionHelper.GetExpressionText((LambdaExpression)expression);
var metadata = ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData);
string resolvedLabelText = metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>());
if (string.IsNullOrEmpty(resolvedLabelText))
{
return MvcHtmlString.Empty;
}
var tag = new TagBuilder("label");
tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)));
if (!String.IsNullOrEmpty(suffix))
{
resolvedLabelText = String.Concat(resolvedLabelText, suffix);
}
tag.SetInnerText(resolvedLabelText);

var dictionary = ((IDictionary<string, object>)HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
tag.MergeAttributes<string, object>(dictionary, true);

return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}

#endregion

#region 复选框扩展 joe add
/// <summary>
/// 复选框扩展
/// </summary>
/// <typeparam name="TModel">模型类型</typeparam>
/// <typeparam name="TProperty">属性类型</typeparam>
/// <param name="helper">HTML辅助方法。</param>
/// <param name="expression">lambda表达式。</param>
/// <param name="selectList">选择项。</param>
/// <param name="htmlAttributes">HTML属性。</param>
/// <returns>返回复选框MVC的字符串。</returns>
public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
IDictionary<string, object> htmlAttributes = null)
{
if (selectList == null || expression == null)
{
return MvcHtmlString.Empty;
}
string name = ExpressionHelper.GetExpressionText(expression);
object obj = helper.ViewData.Eval(name);
string values = "," + obj + ",";
StringBuilder sb = new StringBuilder();
int index = 0;
foreach (var item in selectList)
{
TagBuilder tag = new TagBuilder("input");
tag.MergeAttributes<string, object>(htmlAttributes);
tag.MergeAttribute("type", "checkbox", true);
tag.MergeAttribute("name", name, true);
tag.MergeAttribute("id", name + index, true);
tag.MergeAttribute("value", item.Value, true);
if (values.IndexOf("," + item.Value + ",") > -1)
{
tag.MergeAttribute("checked", "checked", true);
}
sb.AppendLine(tag.ToString(TagRenderMode.SelfClosing) + " ");
TagBuilder label = new TagBuilder("label");
label.MergeAttribute("for", name + index);
label.InnerHtml = item.Text;
sb.AppendLine(label.ToString());
index++;
}
return new MvcHtmlString(sb.ToString());
}

/// <summary>
/// 复选框扩展。
/// </summary>
/// <typeparam name="TModel">模型类型。</typeparam>
/// <typeparam name="TProperty">属性类型。</typeparam>
/// <param name="helper">HTML辅助方法。</param>
/// <param name="expression">lambda表达式。</param>
/// <param name="selectList">选择项。</param>
/// <param name="htmlAttributes">HTML属性。</param>
/// <returns>返回复选框MVC的字符串。</returns>
public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
object htmlAttributes)
{
return helper.CheckBoxListFor<TModel, TProperty>(expression, selectList, new RouteValueDictionary(htmlAttributes));
}

public static MvcHtmlString MultiCheckBoxListFor<TModel, TProperty, TValue>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
Func<TValue, string> getValue = null,
IDictionary<string, object> htmlAttributes = null) where TProperty : IEnumerable<TValue>
{
if (selectList == null || expression == null)
{
return MvcHtmlString.Empty;
}
string name = ExpressionHelper.GetExpressionText(expression);
var values = new List<string>();
var obj = helper.ViewData.Eval(name) as IEnumerable<TValue>;

if (obj != null)
values = getValue == null ? obj.Select(o => o.ToString()).ToList() : obj.Select(getValue).ToList();

StringBuilder sb = new StringBuilder();
int index = 0;
foreach (var item in selectList)
{
TagBuilder tag = new TagBuilder("input");
tag.MergeAttributes<string, object>(htmlAttributes);
tag.MergeAttribute("type", "checkbox", true);
tag.MergeAttribute("name", name, true);
tag.MergeAttribute("id", name + index, true);
tag.MergeAttribute("value", item.Value, true);

if (values.Contains(item.Value))
tag.MergeAttribute("checked", "checked", true);

sb.AppendLine(tag.ToString(TagRenderMode.SelfClosing) + " ");
TagBuilder label = new TagBuilder("label");
label.MergeAttribute("for", name + index);
label.InnerHtml = item.Text;
sb.AppendLine(label.ToString());
index++;
}
return new MvcHtmlString(sb.ToString());
}

#endregion

#region 单选框扩展 mandy add
/// <summary>
/// 单选框扩展
/// </summary>
/// <typeparam name="TModel">模型类型</typeparam>
/// <typeparam name="TProperty">属性类型</typeparam>
/// <param name="helper">HTML辅助方法。</param>
/// <param name="expression">lambda表达式。</param>
/// <param name="selectList">选择项。</param>
/// <param name="htmlAttributes">HTML属性。</param>
/// <returns>返回复选框MVC的字符串。</returns>
public static MvcHtmlString RadioBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
IDictionary<string, object> htmlAttributes = null)
{
if (selectList == null || expression == null)
{
return MvcHtmlString.Empty;
}
string name = ExpressionHelper.GetExpressionText(expression);
object obj = helper.ViewData.Eval(name);
string values = "," + obj + ",";
StringBuilder sb = new StringBuilder();
int index = 0;
foreach (var item in selectList)
{
TagBuilder tag = new TagBuilder("input");
tag.MergeAttributes<string, object>(htmlAttributes);
tag.MergeAttribute("type", "radiobutton", true);
tag.MergeAttribute("name", name, true);
tag.MergeAttribute("id", name + index, true);
tag.MergeAttribute("value", item.Value, true);
if (values.IndexOf("," + item.Value + ",") > -1)
{
tag.MergeAttribute("checked", "checked", true);
}
sb.AppendLine(tag.ToString(TagRenderMode.SelfClosing) + " ");
TagBuilder label = new TagBuilder("label");
label.MergeAttribute("for", name + index);
label.InnerHtml = item.Text;
sb.AppendLine(label.ToString());
index++;
}
return new MvcHtmlString(sb.ToString());
}

/// <summary>
/// 复选框扩展。
/// </summary>
/// <typeparam name="TModel">模型类型。</typeparam>
/// <typeparam name="TProperty">属性类型。</typeparam>
/// <param name="helper">HTML辅助方法。</param>
/// <param name="expression">lambda表达式。</param>
/// <param name="selectList">选择项。</param>
/// <param name="htmlAttributes">HTML属性。</param>
/// <returns>返回复选框MVC的字符串。</returns>
public static MvcHtmlString RadioBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
object htmlAttributes)
{
return helper.CheckBoxListFor<TModel, TProperty>(expression, selectList, new RouteValueDictionary(htmlAttributes));
}
#endregion

public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListOver> listInfo, IDictionary<string, object> htmlAttributes, int number)
{
if (listInfo == null)
{
return null;
}
if (String.IsNullOrEmpty(name))
{

throw new ArgumentException("必须给这些CheckBoxListOver一个Tag Name", "name");

}

if (listInfo == null)
{

throw new ArgumentNullException("必须要设置List<CheckBoxListOver> listInfo");

}

if (listInfo.Count < 1)
{

throw new ArgumentException("List<CheckBoxListOver> listInfo 至少要有一组数据", "listInfo");

}

StringBuilder sb = new StringBuilder();
sb.Append("<table>");
sb.Append("<tr>");
int lineNumber = 0;

foreach (CheckBoxListOver info in listInfo)
{

lineNumber++;
TagBuilder builder = new TagBuilder("input");


if (info.IsChecked)
{

builder.MergeAttribute("checked", "checked");

}

builder.MergeAttributes<string, object>(htmlAttributes);

builder.MergeAttribute("type", "checkbox");

builder.MergeAttribute("value", info.Value);
builder.MergeAttribute("id", "myCheckbox");
builder.MergeAttribute("name", name);

// builder.InnerHtml = string.Format(" {0} ", info.DisplayText);

builder.InnerHtml = "<span style='font-size: 12pt;font-family:宋体'>" + info.DisplayText + "</span>";

sb.Append("<td>");
sb.Append(builder.ToString(TagRenderMode.Normal));
sb.Append("</td>");

if (number == 0)
{

sb.Append("<br />");

}

else if (lineNumber % number == 0)
{
sb.Append("</tr>");
sb.Append("<tr>");
}

}
sb.Append("</tr>");
sb.Append("</table>");
// return new MvcHtmlString(sb.ToString());
return MvcHtmlString.Create(sb.ToString());
}

public static MvcHtmlString CreateGanderRadioButton(this HtmlHelper htmlHelper)
{
StringBuilder str = new StringBuilder();
str.Append("<input type='radio' value=1 name='gender'>男</input>");
str.Append("<input type='radio' value=0 name='gender'>女</input>");
return new MvcHtmlString(str.ToString());
}

}
}

使用的时候:例如:

Action:
public ActionResult AllSubject()
{
var list = _systemEnumService.GetValuesByParentId(SystemEnumConsts.SubjectTypeId);
List<CheckBoxListOver> infos = new List<CheckBoxListOver>();
string AllSubjectID = string.Empty;
if (Session["AllSubjectID"] != null)
{
AllSubjectID = Session["AllSubjectID"].ToString();
}
bool tag = false;
foreach (var item in list)
{
if (!string.IsNullOrEmpty(AllSubjectID) && AllSubjectID.Contains(item.Id.ToString()))
{
tag = true;
}
else
{
tag = false;
}
infos.Add(new CheckBoxListOver(item.Id.ToString(), item.EnumName, tag));
}
infos = infos.OrderBy(s => s.Value).ToList();
ViewData["CheckBoxListOfSubjects"] = infos;
return View();
}

view:
@Html.CheckBoxList("MyCheckbox", (List<CheckBoxListOver>)ViewData["CheckBoxListOfSubjects"], null, 4)

<script>

function GetValue() {
var ss = "";
var r = document.getElementsByName("MyCheckbox");
for (var i = 0; i < r.length; i++) {
if (r[i].checked) {
ss += r[i].value + ",";
}
}
if (ss.length > 0) {
ss = ss.substring(0, ss.length - 1);
}
$("input[name='mdd']").val(ss);
}
</script>
<br />
<input type="hidden" name="mdd" />
<input type="submit" name="save" id="PreSaveId" onclick="return GetValue()" class="k-button" style="65px" value="保存" />
<input type="button" name="SelectAll" id="SelectAll" onclick="return SelectAllChecked()" class="k-button" value="全选/反选" />
}
<script>
function SelectAllChecked() {
var checkboxs = document.getElementsByName("MyCheckbox");
for (var i = 0; i < checkboxs.length; i++) {
var e = checkboxs[i];
e.checked = !e.checked;
}
}
</script>

原文地址:https://www.cnblogs.com/niuzaihenmang/p/5614319.html