C# 将HtmlAttributes添加到HtmlEditorFor()中

C# 将HtmlAttributes添加到HtmlEditorFor()中,c#,html,asp.net,razor,C#,Html,Asp.net,Razor,这是一个棘手的问题,因为我想向EditorFor()添加Html属性,但不想替换已经创建的属性。让我解释一下: 我有一个string.cshtml的默认编辑器模板,其中包含以下代码: @{ var htmlAttributes = ViewData; htmlAttributes["class"] = "text-box single-line form-control"; htmlAttributes["placeholder"] = ViewData.Mode

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

我有一个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添加以下类、占位符和标题,对于表单输入,它非常方便

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

@Html.EditorFor(x => x.Field, new { htmlAttributes = new { disabled = "" } })
当表单输入的字段不是字符串时,它将不会跟随创建的EditorTemplate,并且它将完全使用此代码,但当它是字符串时,EditorTemplate将替换Html属性


有人对此有任何线索吗?

发现有一些愚蠢的错误,首先EditorFor()字段上的声明是错误的,正确的是:

@Html.EditorFor(x => x.Field, new { @disabled = "" })
第二点是在string.cshtml EditorTemplate中继续使用传入的htmlAttributes,替换类属性定义:

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


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

您需要使用EditorTemplate或使用TextBoxFor。事实证明,在EditorFor上创建html属性的方式是错误的,当我改为此方式时,一切正常:@html.EditorFor(x=>x.Field,new{@disabled=”“})编辑模板中的模型应该决定这类事情。
htmlAttributes["class"] = htmlAttributes["class"] + "text-box single-line form-control";