将HtmlAttributes添加到Html EditorFor()

时间:2014-08-19 19:04:28

标签: c# html asp.net razor

这是一个棘手的问题,因为我想将Html属性添加到EditorFor(),但不想替换已经创建的那些。让我解释一下:

我有一个string.cshtml的默认编辑模板,代码如下:

@{    
    var htmlAttributes = ViewData;
    htmlAttributes["class"] = "text-box single-line form-control";
    htmlAttributes["placeholder"] = ViewData.ModelMetadata.Watermark ?? ViewData.ModelMetadata.DisplayName;
    htmlAttributes["title"] = ViewData.ModelMetadata.Watermark ?? ViewData.ModelMetadata.DisplayName;
}
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, htmlAttributes)

它用于始终为表单输入添加以下类,占位符和标题,基于DisplayName DataAnnotation,它非常方便!

但问题是我在使用公共代码添加一个特定表单输入的禁用属性时遇到问题:

@Html.EditorFor(x => x.Field, new { htmlAttributes = new { disabled = "" } })

当Form输入的字段不是字符串时,它不会跟随创建的EditorTemplate,它将使用这个完全代码,但是当它是一个字符串时,EditorTemplate将替换Html属性。

有没有人对此有任何线索?

1 个答案:

答案 0 :(得分:1)

原来有一些愚蠢的错误,首先在EditorFor()字段上的声明是错误的,正确的是这样:

@Html.EditorFor(x => x.Field, new { @disabled = "" })

第二点是继续使用string.cshtml EditorTemplate中的传入htmlAttributes,替换类属性定义:

htmlAttributes["class"] = "text-box single-line form-control";

有关:

htmlAttributes["class"] = htmlAttributes["class"] + "text-box single-line form-control";

通过这种方式,传入的html属性只与新的默认属性连接。