如果你重新使用MVC 3,你可以使用<代码>DisplayAttribute,并且仅使用描述参数。
Public Class User
<Display(Name = "User name", Description = "This is a description")> _
Public Property Name As String
End Class
<System.Runtime.CompilerServices.Extension> _
Public Shared Function HintFor(Of TModel, TValue)(html As HtmlHelper(Of TModel), expression As Expression(Of Func(Of TModel, TValue))) As IHtmlString
Dim attribute = ModelMetadata.FromLambdaExpression(Of TModel, TValue)(expression, html.ViewData)
Return MvcHtmlString.Create(attribute.Description)
End Function
Mvc2
我只是经过了一个奇怪的考验,看看看这一工程是否可行。 (我不经常使用VB并使用在线转换器) 没有任何错误或任何错误,但会产生预期的结果。
<System.Runtime.CompilerServices.Extension()> _
Public Shared Function HintFor(Of TModel, TValue)(html As HtmlHelper(Of TModel), expression As Expression(Of Func(Of TModel, TValue))) As IHtmlString
Dim ex As MemberExpression = DirectCast(expression.Body, MemberExpression)
For Each attribute As Attribute In ex.Expression.Type.GetProperty(ex.Member.Name).GetCustomAttributes(True)
If GetType(System.ComponentModel.DescriptionAttribute) = attribute.[GetType]() Then
Return MvcHtmlString.Create(DirectCast(attribute, System.ComponentModel.DescriptionAttribute).Description)
End If
Next
Dim x = ModelMetadata.FromLambdaExpression(Of TModel, TValue)(expression, html.ViewData)
Return MvcHtmlString.Create(x.Description)
End Function
Additional
我确实不敢肯定,为什么在你能够这样做的时候,我就这样做了。 (尽管我称“MVC 2”可能无法与数据发布妥善合作)
<System.Runtime.CompilerServices.Extension()> _
Public Shared Function HintFor(Of TModel, TValue)(html As HtmlHelper(Of TModel), expression As Expression(Of Func(Of TModel, TValue))) As IHtmlString
Dim x = ModelMetadata.FromLambdaExpression(Of TModel, TValue)(expression, html.ViewData)
Return MvcHtmlString.Create(x.Description)
End Function