Long Cloud Technologies
"... A Yankee in the Land of the Long White Cloud, Aotearoa ..."

How to get to modelmetadata’s additionalvalues and use them in MVC

Got a request from my new client, wanted to have Boolean values map to radio buttons, (no problem, we’ll just make a Shared Boolean.ascx partial view in the EditorsTemplates).  The real kicker came when he asked for a way to attach the labels to use for the yes and no options to the DataModel, which if you think of it makes a lot of sense, because it is a lot easier to ask a True False Question if you can make clear to the user exactly what True means and what False means.

Oh and one other thing, it is very likely that we will end up with boolean that can be Null in the database (yeah I know that maybe we should use an enum with three enumerations for that, but still if the database can do a NULL boolean value, then we should be able to somehow indicate an indeterminate state to the user for a boolean, think tri-state check box).  When you add in the need to possibly have a tri-state boolean, true, false, indeterminate, then it becomes even more clear that labels for the individual radio buttons are necessary to help the user understand clearly what they are being asked.

Of course that means I need to use the DataAnnotations, we basically want to see something like this:

[DisplayName( "NZ Tui Beer?" )]

[DisplayBooleanChoicesAttribute(DisplayChoiceFalse="No", DisplayChoiceTrue="Yes", DisplayChoiceNull="Not Sure, came in glass")]

public bool IsGoodNZBeer { get; set; }

That means I need to figure out and understand the DataAnnotation provider model… Oy Vay, someday my brain is going to explode!  I keep getting these tasks to do things that aren’t really well documented.  As I started down this path, looking behind the curtain when running the app, to see what exactly can I do with DataAnnotations I see they have an AdditionalValues column

clip_image002

That looks like it could be very helpful so it’s off to find some, and I come across the following two links

Now they both involve overriding the DataAnnotationsModelMetadataProvider with a custom class, but they look at the world a little differently.  In the end I implemented the first link’s solution because it was more complete comprehensive walk thru and required less skull sweat.  Having said that, while preparing this blog entry I really started looking closely at that second link and I think it may be a better way to go about this.  I’ll let you know how it eventually turns out.

Closing Note:

Due to loosing the fight against protecting my blog comments from the bloody spammers.  I’ve given up and just shut them off.  If you would like to comment you can reach me on twitter at @matthewhintzen.

Posted on 25 Apr 10 18:35 by matthew.hintzen |

Bookmark this post with:

E-mail | Comments(0) | Comment RSS