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
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.