【发布时间】:2016-03-21 15:06:03
【问题描述】:
public static IHtmlString CheckBoxWithLabelFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression, string labelText, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
object currentValue = metadata.Model;
string property = ExpressionHelper.GetExpressionText(expression);
var checkBox = new TagBuilder("input");
checkBox.AddCssClass("checkBoxWithLabel");
checkBox.GenerateId(property);
checkBox.Attributes["type"] = "checkbox";
checkBox.Attributes["name"] = property;
checkBox.Attributes["value"] = "true";
checkBox.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),false);/*added false*/
var hidden = new TagBuilder("input");
hidden.Attributes["type"] = "hidden";
hidden.Attributes["name"] = property;
hidden.Attributes["value"] = "false";
if (Equals(currentValue, true))
{
checkBox.Attributes["checked"] = "checked";
}
var label = new TagBuilder("label");
label.AddCssClass("checkBoxLabel");
var htmlText = label.ToString().Replace("</label>", "");
htmlText += checkBox.ToString(TagRenderMode.SelfClosing);
htmlText += hidden.ToString(TagRenderMode.SelfClosing);
htmlText += labelText + "</label>";
return new HtmlString(htmlText);
AnonymousObjectToHtmlAttributes(htmlAttributes) 仅将“_”替换为“-”。而 MergeAttributes 需要一个键/值类型,因此忽略现有值。无法将对象 HtmlAttributes 更改/转换为具有 IEnumerable、IDictionary 等的字典。我认为 MergeAttributes 应该在循环中提取键/值,但不确定是什么开始滚动?
我希望类具有初始 htmlAttributes 值“editableInNew editableInUpdate readonly”元素以及使用 .AddCssClass 添加的“checkBoxWithLabel”,但无法使其正常工作,我很难过。
【问题讨论】:
-
是的,该回家了
-
是的,是时候回家了,肯定是 mecek...
@Html.CheckBoxWithLabelFor(x => x.Tra..., "Yes", new { @readonly="", @class = "editableInNew editableInUpdate readonly" })将鼠标悬停在 htmlAttributes 上会得到{ readonly="", class="editableInNew editableInUpdate readonly"}我有标准复选框,其中包含在该工作中传递的属性,并且几乎完全相同,即@Html.CheckBoxFor(x => x.ThirdParty.IsCompany, new { @class = "editableInUpdate editableInNew readonly" })
标签: c# html asp.net-mvc html-helper