Tuesday, February 8, 2011

In ASP.NET MVC, how to write model so checkbox in view corresponds to integer in database?

I have a database column "WantsReply" that logically holds a boolean (bit) but is unfortunately implemented as an integer. Any nonzero value means "yes" and zero means "no".

If I write

class Entry {
   [Column] public int WantsReply {get; set;}
}

in my model, and map it to a checkbox in the view using

Html.CheckBox( "WantsReply", View.Model.WantsReply )

then I get a conversion error when I submit the view. On the other hand if I write

[Column] public bool WantsReply {get; set;}

then the view submit works OK but then I get a different conversion error when I run a query like

from entry in Entries select entry;

How can I resolve this impedance mismatch so that both queries and submits work?

  • Instead of changing the type of the column property, why not map it to a new property?

    public partial class Entry {
        public bool WantsReplyAsBool
        {
            get
            {
                return WantsReply != 0;
            }
            set
            {
                if (value)
                {
                    WantsReply = 1;
                }
                else
                { 
                    WantsReply = 0;
                }
            }
        } 
    }
    

    The integer property can be private, if you like. Use the bool property in your view.

0 comments:

Post a Comment