MVC小系列(十八)【给checkbox和radiobutton添加集合的重载】
mvc对DropDownListFor的重载很多,但对checkbox和radiobutton没有对集合的重载
所以该讲主要针对集合的扩展:
#region 复选框扩展
/// <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 = ;
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 + ",") > -)
{
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));
}
#endregion #region 单选框扩展
/// <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 = ;
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 + ",") > -)
{
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));
} /// <summary>
/// 自定义扩展方法
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="name"></param>
/// <param name="listInfos"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListOver> listInfos, IDictionary<string, object> htmlAttributes)
{ if (string.IsNullOrEmpty(name))
{ throw new ArgumentException("此参数不能为空", "name"); } if (listInfos == null)
{ throw new ArgumentException("listInfos"); } StringBuilder sb = new StringBuilder(); foreach (CheckBoxListOver info in listInfos)
{ TagBuilder builder = new TagBuilder("input"); if (info.IsChecked)
{ builder.MergeAttribute("checked", "checked"); } builder.MergeAttributes(htmlAttributes); builder.MergeAttribute("type", "checkbox"); builder.MergeAttribute("name", name); builder.InnerHtml = info.DisplayText; sb.Append(builder.ToString(TagRenderMode.Normal)); sb.Append("<br />"); }
return new MvcHtmlString(sb.ToString());
} ///// <summary>
///// 重载方法:不含属性键值对集合
///// </summary>
///// <param name="htmlHelper"></param>
///// <param name="name"></param>
///// <param name="listInfos"></param>
///// <returns></returns>
// public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, // List<CheckBoxListOver> listInfos) // { // return htmlHelper.CheckBoxList(name, listInfos, null); // } ///// <summary>
// /// 重载方法:从路由中拿数据
///// </summary>
///// <param name="htmlHelper"></param>
///// <param name="name"></param>
///// <param name="listInfos"></param>
///// <param name="htmlAttributes"></param>
///// <returns></returns>
// public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, // List<CheckBoxListOver> listInfos, object htmlAttributes) // { // return htmlHelper.CheckBoxList(name, listInfos, // ((IDictionary<string, object>) new RouteValueDictionary(htmlAttributes))); // } public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListOver> listInfo)
{
return htmlHelper.CheckBoxList(name, listInfo, (IDictionary<string, object>)null, );
} public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListOver> listInfo, object htmlAttributes) { return htmlHelper.CheckBoxList ( name, listInfo, (IDictionary<string, object>)new RouteValueDictionary(htmlAttributes), ); } //public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListOver> listInfo, IDictionary<string, object> htmlAttributes) //{ // if (String.IsNullOrEmpty(name)) // { // throw new ArgumentException("必须给CheckBoxList一个Tag Name", "name"); // } // if (listInfo == null) // { // throw new ArgumentNullException("必须要设置List<CheckBoxListInfo> listInfo"); // } // if (listInfo.Count < 1) // { // throw new ArgumentException("List<CheckBoxListInfo> listInfo 至少要一组资料", "listInfo"); // } // StringBuilder sb = new StringBuilder(); // 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("name", name); // builder.InnerHtml = string.Format(" {0} ", info.DisplayText); // sb.Append(builder.ToString(TagRenderMode.Normal)); // sb.Append("</br>"); // } // return new MvcHtmlString(sb.ToString()); //} 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 < ) { throw new ArgumentException("List<CheckBoxListOver> listInfo 至少要有一组数据", "listInfo"); } StringBuilder sb = new StringBuilder();
sb.Append("<table>");
sb.Append("<tr>");
int lineNumber = ; 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 == )
{ sb.Append("<br />"); } else if (lineNumber % number == )
{
sb.Append("</tr>");
sb.Append("<tr>");
} }
sb.Append("</tr>");
sb.Append("</table>");
return new MvcHtmlString(sb.ToString());
} #endregion #region 单选框和复选框的扩展
/// <summary>
/// 复选框,selValue为选中项
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="name"></param>
/// <param name="selectList"></param>
/// <param name="selValue"></param>
/// <returns></returns>
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, IEnumerable<string> selValue)
{
return CheckBoxAndRadioFor<object, string>(name, selectList, false, selValue);
}
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string selValue)
{
return CheckBox(htmlHelper, name, selectList, new List<string> { selValue }); }
/// <summary>
/// 复选框
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="name"></param>
/// <param name="selectList"></param>
/// <returns></returns>
public static MvcHtmlString CheckBoxFor(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList)
{
return CheckBox(htmlHelper, name, selectList, new List<string>());
}
/// <summary>
/// 根据列表输出checkbox
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <param name="htmlHelper"></param>
/// <param name="expression"></param>
/// <param name="selectList"></param>
/// <returns></returns>
public static MvcHtmlString CheckBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
return CheckBoxFor(htmlHelper, expression, selectList, null);
} /// <summary>
/// 根据列表输出checkbox,selValue为默认选中的项
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <param name="htmlHelper"></param>
/// <param name="expression"></param>
/// <param name="selectList"></param>
/// <param name="selValue"></param>
/// <returns></returns>
public static MvcHtmlString CheckBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string selValue)
{
string name = ExpressionHelper.GetExpressionText(expression);
return CheckBoxAndRadioFor<TModel, TProperty>(name, selectList, false, new List<string> { selValue });
}
/// <summary>
/// 输出单选框和复选框
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <param name="expression"></param>
/// <param name="selectList"></param>
/// <param name="isRadio"></param>
/// <param name="selValue"></param>
/// <returns></returns>
static MvcHtmlString CheckBoxAndRadioFor<TModel, TProperty>(
string name,
IEnumerable<SelectListItem> selectList,
bool isRadio,
IEnumerable<string> selValue)
{
StringBuilder str = new StringBuilder();
int c = ;
string check, activeClass;
string type = isRadio ? "Radio" : "checkbox"; foreach (var item in selectList)
{
c++;
if (selValue != null && selValue.Contains(item.Value))
{
check = "checked='checked'";
activeClass = "style=color:red";
}
else
{
check = string.Empty;
activeClass = string.Empty;
}
str.AppendFormat("<span><input type='{3}' value='{0}' name={1} id={1}{2} " + check + "/>", item.Value, name, c, type);
str.AppendFormat("<label for='{0}{1}' {3}>{2}</lable></span>", name, c, item.Text, activeClass); }
return MvcHtmlString.Create(str.ToString());
} public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, IEnumerable<string> selValue)
{
return CheckBoxAndRadioFor<object, string>(name, selectList, true, selValue);
}
/// <summary>
/// 单选按钮组,seletList为选中项
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="name"></param>
/// <param name="selectList"></param>
/// <param name="selValue"></param>
/// <returns></returns>
public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string selValue)
{
return RadioButton(htmlHelper, name, selectList, new List<string> { selValue });
}
/// <summary>
/// 单选按钮组
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="name"></param>
/// <param name="selectList"></param>
/// <returns></returns>
public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList)
{
return RadioButton(htmlHelper, name, selectList, new List<string>());
}
/// <summary>
/// 根据列表输出radiobutton
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <param name="htmlHelper"></param>
/// <param name="expression"></param>
/// <param name="selectList"></param>
/// <returns></returns>
public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
return RadioButtonFor(htmlHelper, expression, selectList, new List<string>());
}
public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IEnumerable<string> selValue)
{
string name = ExpressionHelper.GetExpressionText(expression);
return CheckBoxAndRadioFor<TModel, TProperty>(name, selectList, true, selValue);
}
/// <summary>
/// 根据列表输出radiobutton,selValue为默认选中的项
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <param name="htmlHelper"></param>
/// <param name="expression"></param>
/// <param name="selectList"></param>
/// <param name="selValue"></param>
/// <returns></returns>
public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string selValue)
{
return RadioButtonFor(htmlHelper, expression, selectList, new List<string> { selValue });
}
#endregion
再来点其他的扩展,
#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 > )
{
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 = ; 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 = ; 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 : BaseYipondEntityModel
{
return DeleteConfirmation<T>(helper, "", buttonsSelector);
}
public static MvcHtmlString DeleteConfirmation<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipondEntityModel
{
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("Admin.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());
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="helper"></param>
/// <param name="actionName"></param>
/// <param name="buttonsSelector"></param>
/// <returns></returns>
public static MvcHtmlString DeleteConfirmation<T>(this HtmlHelper<T> helper, string actionName, int itemId,
string buttonsSelector) where T : BaseYipondEntityModel
{
if (String.IsNullOrEmpty(actionName))
actionName = "Delete";
var modalId = MvcHtmlString.Create(helper.ViewData.ModelMetadata.ModelType.Name.ToLower() + "-delete-confirmation")
.ToHtmlString();
var deleteConfirmationModel = new DeleteConfirmationModel
{
Id = itemId,
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("Admin.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 : BaseYipondEntityModel
{
return DeleteBrandCateConfirmation<T>(helper, "", buttonsSelector);
}
public static MvcHtmlString DeleteBrandCateConfirmation<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipondEntityModel
{
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("Admin.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 : BaseYipondEntityModel
{
return DeleteConfirmationInfo<T>(helper, "", buttonsSelector);
}
public static MvcHtmlString DeleteConfirmationInfo<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipondEntityModel
{
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("Admin.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 : BaseYipondEntityModel
{
return DeleteConfirmationJLInfo<T>(helper, "", buttonsSelector);
}
public static MvcHtmlString DeleteConfirmationJLInfo<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipondEntityModel
{
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("Admin.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 : BaseYipondEntityModel
{
return DeleteConfirmationSellerInfo<T>(helper, "", buttonsSelector);
}
public static MvcHtmlString DeleteConfirmationSellerInfo<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipondEntityModel
{
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("Admin.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 : BaseYipondEntityModel
{
return DeleteConfirmationStoreInfo<T>(helper, "", buttonsSelector);
}
public static MvcHtmlString DeleteConfirmationStoreInfo<T>(this HtmlHelper<T> helper, string actionName,
string buttonsSelector) where T : BaseYipondEntityModel
{
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("Admin.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 YipondLabelFor<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("YipondResourceDisplayName", out value))
{
var resourceDisplayName = value as YipondResourceDisplayName;
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 > )
{
//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 > )
{
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 < )
indexToSelect = ;
//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("Yipond.Info.Fileds.Day");
monthLocale = locService.GetResource("Yipond.Info.Fileds.Month");
yearLocale = locService.GetResource("Yipond.Info.Fileds.Year");
}
else
{
dayLocale = "Day";
monthLocale = "Month";
yearLocale = "Year";
}
days.AppendFormat("<option value='{0}'>{1}</option>", "", "");
for (int i = ; i <= ; 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>", "", "");
for (int i = ; i <= ; 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>", "", "");
if (beginYear == null)
beginYear = CommonHelper.GetDateTimeNow().Year - ;
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);
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("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>", "", dayLocale);
for (int i = ; i <= ; 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>", "", monthLocale);
for (int i = ; i <= ; i++)
{
months.AppendFormat("<option value='{0}'{1}>{2}</option>",
i,
(selectedMonth.HasValue && selectedMonth.Value == i) ? " selected=\"selected\"" : null,
CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(i));
}
years.AppendFormat("<option value='{0}'>{1}</option>", "", yearLocale);
if (beginYear == null)
beginYear = CommonHelper.GetDateTimeNow().Year - ;
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(daysList, monthsList, yearsList));
}
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
MVC小系列(十八)【给checkbox和radiobutton添加集合的重载】的更多相关文章
- MVC小系列(八)【改变Areas的FindView顺序】
MVC小系列(八)[改变Areas的FindView顺序] 一般项目比较大的话,会根据模块建立Areas,这样结构清晰,也有利于路由的部署, 1 Areas下有自己的_LayOut模板,而如果希望所有 ...
- Web 前端开发精华文章集锦(jQuery、HTML5、CSS3)【系列十八】
<Web 前端开发精华文章推荐>2013年第六期(总第十八期)和大家见面了.梦想天空博客关注 前端开发 技术,分享各种增强网站用户体验的 jQuery 插件,展示前沿的 HTML5 和 C ...
- MVC小系列(七)【分部视图中的POST】
MVC小系列(七)[分部视图中的POST] 在PartialView中进行表单提交的作用:1 这个表单不止一个地方用到,2 可能涉及到异步的提交问题 这两种情况都可能需要把表单建立在分部视图上, 使用 ...
- 为什么不建议给MySQL设置Null值?《死磕MySQL系列 十八》
大家好,我是咔咔 不期速成,日拱一卒 之前ElasticSearch系列文章中提到了如何处理空值,若为Null则会直接报错,因为在ElasticSearch中当字段值为null时.空数组.null值数 ...
- 学习ASP.NET Core Razor 编程系列十八——并发解决方案
学习ASP.NET Core Razor 编程系列目录 学习ASP.NET Core Razor 编程系列一 学习ASP.NET Core Razor 编程系列二——添加一个实体 学习ASP.NET ...
- MVC小系列(二十二)【MVC的Session超时,导致的跳转问题】
由于mvc内部跳转机制的问题,它只在当前的action所渲染的view上进行跳转,如果希望在当前页面跳,需要将mvc方法改为js方法: filterContext.Result = new Redir ...
- MVC小系列(十六)【在控制器级别或具体Action级别上动态设定模板页(Layout)】
方法就是使用:ActionFilterAttribute它的几个方法:OnActionExecuted,OnActionExecuting,OnResultExecuted和OnResultExecu ...
- MVC小系列(十五)【MVC+ZTree实现对树的CURD及拖拽操作】
根据上一讲的可以加载一棵大树,这讲讲下如果操作这颗大树 <link href="../../Scripts/JQuery-zTree/css/zTreeStyle/zTreeStyle ...
- MVC小系列(十二)【RenderAction和RenderPartial区别】
二者作用:RenderAction:渲染分部视图到页面上,要求提供Action和控制器名称RenderPartial:渲染分部视图到页面上,要求提供分部视图的名称,即路径,如果是在当前控制下或者sha ...
随机推荐
- 查看linux虚拟机ssh服务是否开启
知识准备: 1.ssh和sshd的区别: 2.ssh服务进程默认地址:/etc/init.d/ssh 查看ssh服务是否开启 service ssh status 或者: /etc/init.d/ss ...
- c++ 11 key note
*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...
- 2015年9月29日html基础加强学习笔记
创建一个最简便的浏览器 首先打开VS2010,然后在空间里拖出一个Form控件当主页面,其次拖出一个Textbox控件作为地址栏,然后加一个Button控件作为按钮,最后拖出一个WebBrowser作 ...
- Java笔记(六)……程序流程控制
判断结构 三种结构: 1: if(条件表达式) 2: { 3: 执行语句; 4: } 5: 6: if(条件表达式) 7: { 8: 执行语句; 9: } 10: else 11: { 12: 执行 ...
- iOS开发——GCD多线程详解
GCD多线程详解 1. 什么是GCD Grand Central Dispatch 简称(GCD)是苹果公司开发的技术,简单来说,GCD就是iOS一套解决多线程的机制,使用GCD能够最大限度简化多线程 ...
- codeforce 621C Wet Shark and Flowers
题意:输入个n和质数p,n个区间,每个区间可以等概率的任选一个数,如果选的这个区间和它下个区间选的数的积是p的倍数的话(n的下个是1),就挣2000,问挣的期望 思路:整体的期望可以分成每对之间的期望 ...
- (原)Struts 相关资源下载
官网:http://struts.apache.org 点击[Download],进入页面如下,可以看到下载的资源: 点击[struts-2.3.20-all.zip],就能获取Struts2项目所有 ...
- POJ2192 - Zipper(区间DP)
题目大意 给定三个字符串s1,s2,s3,判断由s1和s2的字符能否组成字符串s3,并且要求组合后的字符串必须是s1,s2中原来的顺序. 题解 用dp[i][j]表示s1的前i个字符和s2的前j个字符 ...
- Error message “Assembly must be registered in isolation” when registering Plugins in Microsoft Dynamics CRM 2011 2013 解决办法
Error message “Assembly must be registered in isolation” when registering Plugins in Microsoft Dynam ...
- glance image cache
The Glance Image Cache The Glance API server may be configured to have an optional local image cache ...