3

I have a custom HtmlHelper extension, which renders controls based on teh helper input parameters.

I am in a situation, where, I am able to render any control, except a CheckBox. As the CheckBoxFor helper accepts, Expression<Func<TModel, bool>>

I need a way to convert the return-type of the Func to bool, as mentioned in the title.

4

1 回答 1

6

您可以翻译 lambda:

public static class HtmlExtensions
{
    public static IHtmlString MyHelper<TModel, TProperty>(
        this HtmlHelper<TModel> html, 
        Expression<Func<TModel, TProperty>> ex
    )
    {
        if (typeof(TProperty) != typeof(bool))
        {
            throw new InvalidOperationException("You can only generate checkboxes with boolean properties on your view model");
        }

        var boolExpression = Expression.Lambda<Func<TModel, bool>>(ex.Body, ex.Parameters);

        return html.CheckBoxFor(boolExpression);
    }
}

现在您可以在模型的布尔属性上使用帮助器:

@Html.MyHelper(x => x.SomeBooleanProperty)
于 2013-10-03T11:37:51.000 回答