【问题标题】:How propagate HTMLAttributes to a custom EditorTemplate?如何将 HTMLAttributes 传播到自定义 EditorTemplate?
【发布时间】:2016-11-30 12:50:09
【问题描述】:

我为 currency 这样的浮点格式创建了一个编辑器模板。

@using System.Globalization
@{
    var ri = new RegionInfo(System.Threading.Thread.CurrentThread.CurrentUICulture.LCID);
}

<div class="input-group ">
    <div class="input-group-addon">@ri.CurrencySymbol</div>
    @Html.TextBox("", ViewData.ModelMetadata.Model, new { @class = " form-control text-box single-line" })
</div>

显示带有货币符号的引导输入组

它工作正常,但我试图传递一些额外的类,如“text-danger”或“input-group-lg”,但是这些参数没有传递给编辑器模板。

@Html.EditorFor(model => model.money, new { htmlAttributes = new { @class = "text-danger input-lg form-group-lg" } })

“text-danger input-lg form-group-lg”类未设置为主 div。

如何将这些类传播到我的编辑器模板?

【问题讨论】:

  • 你为什么类型制作了这个编辑器? (浮点数,整数,字符串)
  • 您可以尝试在模板上使用像(string)ViewData["ClassText"] 这样的ViewData,@Html.TextBox("", ViewData.ModelMetadata.Model, new { @class = " form-control text-box single-line " + (string)ViewData["ClassText"] 然后在编辑器上使用它会像这样@Html.EditorFor(model =&gt; model.money, new { ClassText = "text-danger input-lg form-group-lg" })
  • @FelipeDeguchi 浮动
  • 您需要将属性传递为additionalViewData(而不是HtmlAttributes)并读取EditorTemplate 中的ViewData 并将值添加到您的html。
  • 我个人不喜欢将 css 类传递给模板(EditorFor/DisplayFor)。如果您的模板很复杂,您还会应用哪些 HTML 节点的值呢?模棱两可,如果你更改模板,其他模板/页面如何调用该模板,那简直就是一场噩梦,所以我从不建议这样做。

标签: c# asp.net-mvc razor mvc-editor-templates


【解决方案1】:

只需使用路由 ViewData["htmlAttributes"] 到字典并获取“类”值

@{
    var htmlAttrib = ViewData["htmlAttributes"]
    IDictionary<string, object> dic = new RouteValueDictionary(htmlAttrib);
    var classes = dic ["class"];
}

<div class="@classes" > your control .... </div> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2020-07-25
    相关资源
    最近更新 更多