简体   繁体   English

将HtmlAttributes添加到Html EditorFor()

[英]Add HtmlAttributes to Html EditorFor()

That is a tricky question because I want to add Html Attributes to the EditorFor() but do not want to replace the ones that was already created. 这是一个棘手的问题,因为我想将HTML属性添加到EditorFor(),但不想替换已经创建的属性。 Let me explain: 让我解释:

I have a default Editor Template for string.cshtml with the following code: 我具有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)

It is used to always add the following class, placeholder and title, based on the DisplayName DataAnnotation, for the Form Inputs, it is quite handy! 它总是用于根据DisplayName DataAnnotation添加以下类,占位符和标题,用于表单输入,这非常方便!

But the problem is that I'm having trouble adding the disable attribute for one specific Form Input with the common code: 但是问题是我无法使用通用代码为一个特定的Form Input添加disable属性:

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

When the Form Input is with a field that is not a string, it will not follow the created EditorTemplate and it will work with this exactly code, but when it is a string, the EditorTemplate replaces the Html Attributes. 当Form Input的字段不是字符串时,它将不跟随创建的EditorTemplate,并且将使用此完全相同的代码,但是当它是字符串时,EditorTemplate将替换Html属性。

Does anyone has any clue on this? 有人对此有任何线索吗?

Turns out there was a few dumb errors, first of all the declaration on the EditorFor() field was wrong, the correct one is this: 原来有一些愚蠢的错误,首先在EditorFor()字段上的声明是错误的,正确的是:

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

The second point is to keep using the incoming htmlAttributes in the string.cshtml EditorTemplate, replacing the class property definition: 第二点是继续使用string.cshtml EditorTemplate中传入的htmlAttributes,替换类属性定义:

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

For: 对于:

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

In this way, the incoming html attributes is just concatenated with the new default ones. 这样,传入的html属性仅与新的默认属性连接在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM