【发布时间】:2014-12-04 20:34:48
【问题描述】:
我在我开始的一个新项目中使用 bootstrap 5,我决定创建一个包装器来自动为我完成这项工作,而不是围绕表单字段编写所有脚手架。
我对 textboxfor、textareafor 和 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;
}
然后可以如下调用:
@FormHelpers.MyTextBoxFor(Html, x => x.Name)
但是这似乎不适用于 checkbox:
Error 1 'System.Web.Mvc.HtmlHelper<TModel>' does not contain a definition for 'CheckBoxFor' and the best extension method overload 'System.Web.Mvc.Html.InputExtensions.CheckBoxFor<TModel>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,bool>>)' has some invalid arguments
如果我将TProperty 更改为bool,它将编译,但我在调用此帮助程序的那一行出现运行时错误:
CS0411: The type arguments for method 'CollectionSystem.Helpers.FormHelpers.MyCheckboxFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,bool>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
请有人告诉我如何包装 CheckboxFor 函数。
【问题讨论】:
-
也许这会有所帮助:stackoverflow.com/a/56256649/5836671
标签: c# asp.net-mvc asp.net-mvc-4