如何从扩展方法访问ValidationMessageFor

时间:2011-05-10 18:24:45

标签: 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.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

...

实际上这是因为我想生成像这样的mvcHtmlString

<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>

提前问候

1 个答案:

答案 0 :(得分:0)

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

这将允许您对任何型号使用该扩展名,并且您的通话不会更改。我不完全确定你问的是什么。

**@Html.Asistente(Function(model) model.Numero)**

(请注意,vb是使用c#到vb转换器生成的 - 但它看起来是正确的)

如果您想使用您发布的第一个样本,那么您将不得不写下这样的内容:

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表达式属性,因此不会编译。