Is there a way to wrap Html.CheckboxFor, Html.TextboxFor, etc. methods with custom logic?

asp.net-mvc asp.net-mvc-3 expression-trees linq

Question

I am working with legacy models that wrap data and meta-data up in a single property. For the purpose of this question, suppose the interface is:

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

I want to wrap the CheckBoxFor() extension method with my own,

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"
}

Is there a way to do something like this? Where would I start?

Any help would be appreciated,

Thanks,
Alex

Popular Answer

You could try something like this:

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"});
}

You may also wish to cache the compiled expression.

My example uses Html.CheckBox(); I'm not sure how to go about utilising CheckBoxFor(). I haven't got time to investigate it either, but atleast this is somewhere to start.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why