【问题标题】:How to display name of MVC model?如何显示 MVC 模型的名称?
【发布时间】:2015-03-16 05:13:43
【问题描述】:

我有这样的课:

Public Class AuthKey
    <StringLength(45, ErrorMessage:="Name must not less then 5 characters and not exceed 45 characters.", MinimumLength:=5)>
    <Display(Name:="Name", Description:="Authentication name.")> _
    Public Property name As String
End Class

我想查看属性显示名称和描述,而不是属性值。我尝试 @html.display("Name") 或 @html.display("Description") 和 @html.displayfor(function (m) m.name) 都什么都不显示。如何展示?

【问题讨论】:

  • 如果您的模型“名称”属性包含任何值,则 Display/DisplayFor 将显示文本
  • 不,我想显示“名称”和/或“身份验证名称”。价值。就像我使用 html.labelfor 一样,它会显示如下标签名称:。我只想要名称的纯文本,没有任何 html 标记。
  • 使用DisplayNameFor()
  • @BennyChen,它不被任何内置助手直接使用,但您可以创建自己的或从ViewData.ModelMetadata 访问。 answers here 显示几个选项
  • @StephenMuecke,感谢您的链接。有用!我最终通过直接访问元数据而不是创建新的自定义帮助程序。所以这里是:@ModelMetadata.FromLambdaExpression(Of AuthKey, String)(Function(model) model.name, ViewData).Description

标签: asp.net-mvc model-view-controller html-helper


【解决方案1】:

在您的视图页面中添加模型类,然后像这样尝试

 @Html.DisplayNameFor(model => model.name)

how-to-access-the-model-from-the-view

【讨论】:

  • 这将显示名称,但不显示描述。 @stephenmuecke 方法有效。我需要创建自定义助手或直接访问元数据。
  • @BennyChen,我只评论了。根据您的原始问题,此答案是正确的,您应该将其标记为已接受
猜你喜欢
  • 2020-06-10
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
  • 2018-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多