2011-06-09 43 views
1

我正在使用將數據和元數據包裝在單個屬性中的遺留模型。對於這個問題的目的,假設該接口是:有沒有辦法用自定義邏輯來包裝Html.CheckboxFor,Html.TextboxFor等方法?

pubic interface ILegacyCheckbox 
{ 
    bool Value { get; set; } 
    bool Editable { get; set; } 
} 

我想用我自己的包裹CheckBoxFor()擴展方法,

public static MvcHtmlString LegacyCheckboxFor<TModel>(
    this HtmlHelper<TModel> html, 
    Expression<Func<TModel, ILegacyCheckbox>> expression) 
{ 
    // wrap html.CheckBoxFor() method here by extracting the Value 
    // property and check if Editable is false, in which case add 
    // an htmlAttribute of "disabled=true" 
} 

有沒有辦法做這樣的事情?我會在哪裏開始?

任何幫助,將不勝感激,

謝謝,
亞歷

回答

1

你可以嘗試這樣的事:

public static MvcHtmlString LegacyCheckboxFor<TModel>(
this HtmlHelper<TModel> html, 
Expression<Func<TModel, ILegacyCheckbox>> expression) 
{ 
    var parameterName = ((MemberExpression)expression.Body).Member.Name; 
    var compiled = expression.Compile().Invoke(html.ViewData.Model); 

    if (editable) 
     return html.CheckBox(parameterName, compiled.Value); 
    else 
     return html.CheckBox(parameterName, compiled.Value, new {disabled = "disabled"}); 
} 

您也不妨緩存編譯的表達。

我的例子使用Html.CheckBox();我不知道如何去利用CheckBoxFor()。我還沒有時間來調查它,但至少這是一個開始的地方。

+0

謝謝,工作! – afeygin 2011-06-10 16:18:34

+0

我是否需要使用html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName()來包裝parameterName以確保它在foreach循環中有效? – afeygin 2011-06-10 16:20:38

0
public static MvcHtmlString LegacyCheckboxFor<TModel>(
    this HtmlHelper<TModel> html, 
    Expression<Func<TModel, ILegacyCheckbox>> expression) 
{ 
    MemberExpression memberExpression = expression.Body as MemberExpression; 
    string parameterName = memberExpression.Member.Name; 

    var checkbox = expression.Compile().Invoke(html.ViewData.Model); 

    return new MvcHtmlString(
     string.Format(
     "<input type=\"checkbox\" name=\"{0}\" id=\"{0}\" value=\"{1}\" {2} />", 
      parameterName, 
      checkbox.Value, 
      checkbox.Editable ? "disabled=true" : string.Empty)); 
} 
+0

我會使用Html.CheckBox()方法而不是構建字符串! – 2011-06-09 16:08:19

+0

@Simon Bartlett如何在此擴展中引用'Html.CheckBox()'? – 2011-06-09 16:11:30

+0

我已經更新了我的答案,使用Html.CheckBox() – 2011-06-09 16:15:03

相關問題