2012-05-31 50 views
1

我想獲得HtmlHelper.Display方法的MvcHtmlString結果,該方法與我目前的HtmlHelper不同。下面的代碼編譯,但總是返回一個空字符串。撥打不同型號的HtmlHelper.Display

public static MvcHtmlString GetPropertyValue(this HtmlHelper html, string property, object value) 
{ 
    var dictionary = new ViewDataDictionary(); 
    dictionary.Add(property, value); 
    var fooHelper = new HtmlHelper<FooModel>(
     new ViewContext(
      html.ViewContext, 
      new WebFormView(html.ViewContext, "dummy"), 
      dictionary, 
      new TempDataDictionary(), 
      TextWriter.Null), 
     new ViewPage()); 
    return fooHelper.Display(property); 
} 

所有輔助對象(ViewContextsControllerContextsViewDataDictionaries等)類型的黑盒給我;我確定我錯過了一些明顯的東西。

我如何得到這個工作?

對於好奇:這是在我的應用程序審計頁面上使用。我有數據庫中的屬性名稱(作爲string),舊值和新值。我也知道將用於顯示記錄所代表的模型的實際實例的類型。我想重複使用模型類中的所有數據註釋來顯示HTML。

回答

1

我有點兒同樣的問題。我想要的:

我想創建自己的html擴展方法,它會做一些東西,而不是調用DisplayFor。在該方法的顯示中,我會傳遞不同的模型對象。

我的解決方案

public static MvcHtmlString ShowProperty<T>(this HtmlHelper<T> helper, NewModel mynewModel){ 
     return helper.DisplayFor(m => myNewModel, "TemplateName"); 
    } 

Mayby這會工作一段一個