2

I'm creating a strongly typed helper (ref: SO question). As 'commented' in the code below, is it possible to somehow get the value from the expressed property and thus bypass the optional selectedValue parameter?

    <Extension()> _
    Public Function DatePickerFor(Of TModel As Class, TProperty)(ByVal htmlHelper As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of TModel, TProperty)), Optional ByVal selectedValue As Nullable(Of Date) = Nothing) As MvcHtmlString
        Dim inputName = ExpressionHelper.GetExpressionText(expression)
        Dim inputValue = selectedValue 
        //Something like this possible? 
        //inputValue = ExpressionHelper.GetExpressionValue(expression)
        Return DatePicker(htmlHelper, inputName, inputValue)
    End Function
Community
  • 1
  • 1
Ropstah
  • 17,538
  • 24
  • 120
  • 194

1 Answers1

9

If you want to get the value of the corresponding property that the expression is pointing to you could use the FromLambdaExpression method:

Dim metadata = ModelMetadata.FromLambdaExpression(expression)
Dim value = metadata.Model
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 3
    In MVC3 ModelMetaData now seems to requires a ViewData parameter, so try: ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); – Alex Nov 23 '11 at 15:59
  • I used this : expression.Compile().Invoke(html.ViewData.Model); to get value and works fine – Usman Younas May 05 '15 at 10:20