我正在创建一个强类型帮助器(ref:SO question)。如下面的代码中“已评论”,是否可以以某种方式从表达的属性中获取值,从而绕过可选的selectedValue
参数?
<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
答案 0 :(得分:9)
如果要获取表达式指向的相应属性的值,可以使用FromLambdaExpression方法:
Dim metadata = ModelMetadata.FromLambdaExpression(expression)
Dim value = metadata.Model