2011-05-12 24 views
3

確定說,我有以下型號:如何在強類型的HtmlHelper擴展得到的模型表達點部分

public class bar{ 
    public string bar {get; set; } 
} 

public class foo{ 
    public bar mybar{get; set;} 
    public string anotherproperty{get; set;} 
} 

並在UI我想這樣做:

@Html.MyWhackyHelperFor(x=>x.bar) 

這用途:

public static MvcHtmlString MyWhackyHelperFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression){ 
//how can i get a the actual bar object here? 
} 

我如何得到被引用的模型的實際部分?

回答

3

您需要編譯表達式轉換的方法,然後調用方法:

TValue val = expression.Compile()(htmlhelper.ViewData.Model); 
+0

甜蜜。謝謝 - 是TValue val = expression.Compile()(htmlHelper.ViewData.Model);準確地說:) – iwayneo 2011-05-12 11:55:41