【问题标题】:unable to apply Bootstrap classes to my EditorFor无法将 Bootstrap 类应用于我的 EditorFor
【发布时间】:2015-03-14 13:50:39
【问题描述】:

我正在开发一个 asp.net mvc-5 web 应用程序,我写了以下内容:-

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
&
@Html.EditorFor(model => model.Name, new { @class = "form-control"  })

但这不会对生成的 html 产生任何影响,但是如果我将 EditorFor 更改为 TextboxFor 我会得到表单控制类的效果吗?有人可以就此提出建议吗?我读到这仅在 asp.net mvc 5.1 中受支持?那么除了将我的 asp.net mvc-5 升级到 asp.net mvc 5.1 以消除升级风险之外,我可以采用哪些可用的方法来使其正常工作? 有人可以推荐吗?

【问题讨论】:

  • 你看过这个帖子吗:stackoverflow.com/questions/4576209/…
  • 那么我如何修改分配编辑器模板中的类??
  • 你能展示你的编辑器模板代码吗?我引用的那篇文章中接受的答案(有 106 个赞成!)表明为编辑器模板指定“类”没有意义,因为模板可能包含许多标记(与TextboxFor 仅呈现一个标签)。答案还显示了如何将类应用于编辑器模板中的标签。哪一部分不清楚?
  • @johnG,如果要在EditorFor()方法中指定类,可以将其传递为AdditionalViewData,如this answer所示
  • @StephenMuecke 感谢您的回复,但似乎如果我想在编辑器中使用“htmlAttributes”,我需要将我的项目从 mvc5.0 升级到 mvc5.1 或 mvc5.2 。 ..

标签: twitter-bootstrap razor asp.net-mvc-5 html-helper editorfor


【解决方案1】:

是的,要将 html 属性传递给标准 EditorFor(),您需要 MVC-5.1+。如果你想用 MVC-5 复制它,你可以创建一个自定义编辑器模板并使用接受 additionViewData 的重载传递属性。例如,创建一个名为“String.cshtml”的新EditorTemplate,以将模板应用于所有类型为string的属性

/Views/Shared/EditorTemplates/String.cshtml

@Html.TextBoxFor(m => m, ViewData["attributes"])

在视图中

@Html.EditorFor(m => m.Name, new { attributes = new { @class = "form-control" } })

或创建一个特定的EditorTemplate

/Views/Shared/EditorTemplates/MyCustomTemplate.cshtml

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, ViewData["htmlAttributes"])

在视图中

@Html.EditorFor(m => m.Name, "MyCustomTemplate", new { attributes = new { @class = "form-control" } })

第二个示例展示了如何尊重上面 cmets 中提到的 DisplayFormat 属性,例如

[DisplayFormat(DataFormatString="{0:C}", ApplyFormatInEditMode = true)]
public decimal Amount { get; set; }

将值格式化为货币字符串。

This answer 还提供了一些其他选项,包括创建用于呈现引导控件的自定义 html 帮助程序

【讨论】:

  • 感谢您的回复,似乎最简单的方法是将我的 mvc5.0 升级到 mvc 5.2.2 。但是从 asp.net mvc5 升级到 mvc5.2.2 ,包括运行以下命令 Install-Package Microsoft.AspNet.Mvc -Version 5.2.2 ?还是有其他手动步骤?
  • 据我所知,Nuget 包应该正确更新 web.config 文件(适用于 5.0 > 5.1 但我还没有完成 5.2)。检查先决条件here,这样您就不会遇到here 描述的问题。与往常一样,请确保您有备份:)
  • 感谢您的回复。现在我没有使用 webAPi,所以我不需要更新它,这是正确的吗?或者最好将 asp.net mvc 更新到 5.2.2 和 webapi 到 5.2.2 以及 Microsoft.AspNet.WebPages 到版本 3.2.0?
【解决方案2】:

这行得通:

@Html.EditorFor(x => x.Created, new { htmlAttributes = new { @class = "date" } })

【讨论】:

    猜你喜欢
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 2017-12-22
    • 2013-08-08
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多