Sandra S.
Sandra S.

Reputation: 181

asp.net mvc convert Expression<Func<TModel, TProperty>> to Expression<Func<TModel, bool>>

I need to implement a custom helper that will return for a string that can have the value "1" or "0" a CheckBox instead of TextBox. So in custom helper I have:

    public static MvcHtmlString MyCustomHelper<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
      ....
      Expression<Func<TModel, bool>> boolExpression = ??????????

      return helper.CheckBoxFor(boolExpression); 
    }

What should be assigned to 'boolExpression' variable?

Upvotes: 1

Views: 392

Answers (1)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

A ViewModel or a not-mapped property in a partial Model would be the way to go.

You won't be able to use CheckBoxFor on an inexisting property.

Imagine your String property with "0" or "1".

public string MyProperty{get;set;}


private bool myBooleanProperty_;
[NotMapped]
public bool MyBooleanProperty {
 get {
   myBooleanProperty_ = MyProperty == "1";
   return myBooleanProperty_;
}
set {
   myBooleanProperty_ = value;
}

Then you can use

@Html.CheckBoxFor(x => x.MyBooleanProperty)

When you post values in a form, you'll have of course to set a value to MyProperty, depending on value of MyBooleanProperty.

Upvotes: 1

Related Questions