【问题标题】:Add HtmlAttributes to Html EditorFor()将 HtmlAttributes 添加到 Html EditorFor()
【发布时间】:2014-08-20 04:47:39
【问题描述】:

这是一个棘手的问题,因为我想将 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,对于Form Inputs,非常方便!

但问题是我无法使用通用代码为一个特定的表单输入添加禁用属性:

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

当表单输入带有一个不是字符串的字段时,它不会跟随创建的 EditorTemplate 并且它将使用这个确切的代码,但是当它是一个字符串时,EditorTemplate 会替换 Html 属性。

有人对此有任何线索吗?

【问题讨论】:

  • 您需要使用 EditorTemplate 或使用 TextBoxFor。
  • 原来,在 EditorFor 上创建 html 属性的方式是错误的,当我改成这个时,一切正常:@Html.EditorFor(x => x.Field, new { @disabled = "" })
  • 编辑模板中的模型应该决定这种事情。

标签: c# html asp.net razor


【解决方案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 属性只是与新的默认属性连接起来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-10
    • 2011-09-14
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多