好的,最简单的方法是自己编写帮助程序,这并不难,而且您可以完全控制它们,特别是您可以重复使用默认帮助程序调用。例如,对于一个简单的 Boostrap 文本框组,您可以有以下代码:
public static class BootstrapHtmlHelper
{
public static MvcHtmlString TextboxGroupFor<TModel, TProperty>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TProperty>> expression,
string title,
string id,
string placeholder)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<div class=\"form-group\">");
sb.AppendLine("<label for=\"{0}\">{1}</label>", id, title);
sb.AppendLine( htmlHelper.TextBoxFor( expression, new { @class = "form-control", @id = id, @placeholder = placeholder }) );
sb.AppendLine( htmlHelper.ValidationMessageFor( expression );
sb.AppendLine("</div>");
return new MvcHtmlString( sb.ToString() );
}
}
您可以添加任何参数,检查验证,添加帮助框,进行任何格式化等操作。
然后您可以在视图中使用它:
@Html.TextboxGroupFor(x => x.FirstName, "First Name", "first-name-id", "Enter first name...")
更新:
下拉菜单的示例,只需重用ListBoxFor
并传递IEnumerable<SelectListItem>
:
public static class BootstrapHtmlHelper
{
public static MvcHtmlString DropdownGroupFor<TModel, TProperty>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> list,
string selectedValue,
string title,
string id)
{
var selectedList = list.Select(x => x.Value.Equals(selectedValue) ? x.Selected = true : x.Selected = false);
StringBuilder sb = new StringBuilder();
sb.AppendLine("<div class=\"form-group\">");
sb.AppendLine("<label for=\"{0}\">{1}</label>", id, title);
sb.AppendLine( htmlHelper.ListBoxFor( expression, selectedList, new { @class = "form-control", @id = id }) );
sb.AppendLine( htmlHelper.ValidationMessageFor( expression );
sb.AppendLine("</div>");
return new MvcHtmlString( sb.ToString() );
}
}
在视图中:
@Html.DropdownGroupFor(
x => x.Country,
Model.Countries.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id
}));
询问我们推荐或寻找工具、库或最喜爱的站外资源的问题,在 Stack Overflow 上不适合,因为它们往往会吸引持有意见的回答和垃圾信息。
更多细节请参考 这里。 - Christofer Eliasson