问题描述
我使用的引导5在一个新的项目我开始,而非不必编写围绕表单域所有的脚手架,我决定创建一个包装自动为我做到这一点。
I am using bootstrap 5 in a new project I am starting, and rather than having to write all the scaffolding around a form field, I have decided to create a wrapper to do this for me automatically.
我已经使用textboxfor,textareafor和DropDownList的语法如下:
I have used the following syntax for textboxfor, textareafor and dropdownlist:
public static MvcHtmlString MyTextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
var stringbuilder = new MvcHtmlString("<div class='form-group'>" +
helper.LabelFor(expression, new {@class = "col-sm-3 control-label"}) +
"<div class='col-sm-5'>" +
helper.TextBoxFor(expression, new {@class = "form-control"}) +
"</div>" +
"</div>");
return stringbuilder;
}
如下然后可以叫:
Which can then be called as follows:
@ FormHelpers.MyTextBoxFor(HTML,X =&GT; x.Name)
然而,这不会出现对checkboxfor工作:
However this does not appear to work for checkboxfor:
错误1'System.Web.Mvc.HtmlHelper&LT;&的TModel GT;'不包含'CheckBoxFor'和最佳推广方法重载的定义'System.Web.Mvc.Html.InputExtensions.CheckBoxFor<TModel>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Ex pressions.Ex pression&LT; System.Func&LT;的TModel,布尔&GT;&GT;)'有一些无效参数
如果我更改 TProperty
到布尔
它会再编译,但我得到上线,其中运行时错误我把这个助手:
If I change TProperty
to bool
it will then compile, but I get a runtime error on the line where I call this helper:
CS0411:该类型参数的方法'CollectionSystem.Helpers.FormHelpers.MyCheckboxFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Ex pressions.Ex pression&所述; System.Func&下;的TModel,布尔&GT;&GT)'不能从使用中推断出来。尝试显式指定类型参数。
能有人建议我怎么能去包裹CheckboxFor功能吧。
Can someone advise how I can go about wrapping the CheckboxFor function please.
推荐答案
您帮助需要像
public static MvcHtmlString BootstrapCheckBoxFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, bool>> expression)
{
TagBuilder innerContainer = new TagBuilder("div");
innerContainer.AddCssClass("col-sm-5");
innerContainer.InnerHtml = helper.CheckBoxFor(expression, new {@class = "form-control"}).ToString();
StringBuilder html = new StringBuilder();
html.Append(helper.LabelFor(expression, new {@class = "col-sm-3 control-label"}));
html.Append(innerContainer.ToString());
TagBuilder outerContainer = new TagBuilder("div");
outerContainer.AddCssClass("form-group");
outerContainer.InnerHtml = html.ToString();
return MvcHtmlString.Create(outerContainer.ToString());
}
请注意您可能需要编辑这包括 @ Html.ValidationMessageFor()
Note you may want to edit this to include @Html.ValidationMessageFor()
这篇关于创建一个助手来覆盖CheckboxFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!