自定义ASP.NET MVC2 HtmlHelper:如何获取传递给它的对象的实例?

时间:2011-01-18 18:22:52

标签: vb.net asp.net-mvc-2 html-helper

我正在开发一个ASP.NET MVC2网站。用于学习。我正在使用Visual Basic语言。

在一个视图中我想这样做:

 <%: Html.EditorForEnumeracion(Function(v) v.combustible%>

所以,我创建了一个HtmlHelper扩展方法:

Imports System.Runtime.CompilerServices
Imports System.Linq.Expressions
Imports System.Reflection

Public Module HtmlHelpers
    <Extension()> _
    Public Function EditorForEnumeracion(Of TModel, TValue)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of TModel, TValue))) As MvcHtmlString
        'My stuff goes here
     End Function
End Module

问题是我不知道如何获取传递给帮助程序的v.combustible对象的实例。我不关心v对象。我需要使用v对象的可燃属性。

Herehere似乎就是这样做的,但我不明白。另外,我使用的是Visual Basic,而不是C#。

我认为我可以通过表达式参数获取Enumeracion对象的实例,但我不明白如何。

现在有更多信息。

这是我的“Vehiculo”课程:

Namespace Models.Automovil
    Public Class Vehiculo
        Public Property tipo As New Models.Enumeracion("TipoDeVehiculo")
        Public Property marca As String
        Public Property modelo As String
        Public Property numeroDePuertas As Integer
        Public Property combustible As New Models.Enumeracion("TipoDeCombustible")
        Public Property potencia As Integer
        Public Property fechaPrimeraMatriculacion As DateTime
        Public Property version As String
        Public Property precio As Decimal
        Public Property descripcion As String
    End Class
End Namespace

这是我的“Enumeracion”课程:

Namespace Models
    Public Class Enumeracion
        Private bd As New tarificadorasegasaEntities
        Private diccionario As New Dictionary(Of String, Integer)
        Private _nombre As String
        Private _clave As String
        Private _valor As Integer
        Public ReadOnly Property nombre As String
            Get
                Return _nombre
            End Get
        End Property
        Public ReadOnly Property clave As String
            Get
                Return _clave
            End Get
        End Property
        Public ReadOnly Property valor As Integer
            Get
                Return _valor
            End Get
        End Property

        'More stuff here. Methods.

    End Class
End Namespace

该模型是Vehiculo类。

仍未解决此问题。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您需要将表达式编译为Func(Of TModel, TValue),然后在模型上调用它:

Dim func = expression.Compile()
Dim value = func(html.ViewData.Model)

答案 1 :(得分:0)

试试这样:

<Extension()> _
Public Function EditorForMyCustomClassB(Of Vehiculo, Enumeracion)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of Vehiculo, Enumeracion))) As MvcHtmlString
    Dim res = ModelMetadata.FromLambdaExpression(expression, html.ViewData)
    Dim e As Enumeracion = DirectCast(res.Model, Enumeracion)
    ' use e here
 End Function