Asp.net mvc 如何从扩展方法访问ValidationMessageFor
我怎样才能访问html扩展…比如LabelFor、EditorFor、ValidationMessageFor 我正在写我自己的扩展名Asp.net mvc 如何从扩展方法访问ValidationMessageFor,asp.net-mvc,asp.net-mvc-3,razor,extension-methods,Asp.net Mvc,Asp.net Mvc 3,Razor,Extension Methods,我怎样才能访问html扩展…比如LabelFor、EditorFor、ValidationMessageFor 我正在写我自己的扩展名 Imports System Imports System.Web.Mvc Imports System.Web.Mvc.Html Imports System.Web Imports System.Text Public Module HtmlExtensions <System.Runtime.CompilerServices.Extensi
Imports System
Imports System.Web.Mvc
Imports System.Web.Mvc.Html
Imports System.Web
Imports System.Text
Public Module HtmlExtensions
<System.Runtime.CompilerServices.Extension()> _
Public Function Asistente(Of TModel As Class)(ByVal helper As HtmlHelper, model As TModel) As MvcHtmlString
helper.ValidationMessage("Home") 'It works fine
helper.ValidationMessagefor() 'It show the next message 'ValidationMessagefor' is not a member of 'System.Web.Mvc.HtmlHelper
End Function
...
实际上,这是因为我想生成一个这样的mvchtml字符串
<div class="editor-label">
@Html.LabelFor(Function(model) model.Numero)
</div>
<div class="editor-field">
@Html.EditorFor(Function(model) model.Numero)
**@Html.ValidationMessageFor(Function(model) model.Numero)**
</div>
提前考虑ValidationMessageFor方法需要一个泛型类型的html帮助程序。因此,您的方法可能如下所示:
Public Shared Function Asistente(Of TModel, TProperty)(helper As HtmlHelper(Of TModel), expression As Expression(Of Func(Of TModel, TProperty))) As HtmlString
Return helper.ValidationMessageFor(expression)
End Function
Public Shared Function Test(Of T As User)(helper As HtmlHelper(Of T), model As T) As HtmlString
Return helper.ValidationMessageFor(Function(f) f.Name)
End Function
这将允许您对任何型号使用该扩展,并且您的呼叫不会改变。不过我不完全确定你在问什么
**@Html.Asistente(Function(model) model.Numero)**
请注意,vb是使用c到vb转换器生成的,但它看起来是正确的
如果你想使用你发布的第一个示例,那么你必须这样写:
Public Shared Function Asistente(Of TModel, TProperty)(helper As HtmlHelper(Of TModel), expression As Expression(Of Func(Of TModel, TProperty))) As HtmlString
Return helper.ValidationMessageFor(expression)
End Function
Public Shared Function Test(Of T As User)(helper As HtmlHelper(Of T), model As T) As HtmlString
Return helper.ValidationMessageFor(Function(f) f.Name)
End Function
但是,这是一个特定的用例,因为如果不将模型类型强制为特定类型,则不会显示lambda表达式属性,因此也不会编译