Abstracting the interpretation of MVC checkboxes values received by the FormsCollection object

Posted by Simon_Weaver on Stack Overflow See other posts from Stack Overflow or by Simon_Weaver
Published on 2009-02-03T05:18:11Z Indexed on 2010/04/21 4:03 UTC
Read the original article Hit count: 193

Filed under:
|

In ASP.NET MVC a checkbox is generated by the HtmlHelper code here:

<%= Html.CheckBox("List_" + mailingList.Key, true) %>

as this HTML:

<input id="List_NEW_PRODUCTS" name="List_NEW_PRODUCTS" type="checkbox" value="true" />
<input name="List_NEW_PRODUCTS" type="hidden" value="false" />

In case you're wondering why is there an extra hidden field? - then read this. Its definitely a solution that makes you first think 'hmmmmm' but then you realize its a pretty elegant one.

The problem I have is when I'm trying to parse the data on the backend. Well its not so much of a problem as a concern if anything in future were to change in the framework.

If I'm using the built in binding everything is great - its all done for me. But in my case I'm dynamically generating checkboxes with unknown names and no corresponding properties in my model.

So i end up having to write code like this :

if (forms["List_RETAIL_NOTIFICATION"] == "true,false") {

}

or this:

if (forms.GetValues("List_RETAIL_NOTIFICATION")[0] == "true") {

}

Both of which i still look at and cringe - especially since theres no guarantee this will always be the return value. I'm wondering if theres a way to access the layer of abstraction used by the model binders - or if I'm stuck with my controller 'knowing' this much about HTTP POST hacks.

Yes I'm maybe being a little picky - but perhaps theres a better clever way using the model binders that I can employ to read dynamically created checkbox parameters.

In addition i was hoping this this post might help others searcheing for : "true,false". Even though I knew why it does this I just forgot and it took me a little while to realize 'duh'.


FYI: I tried another few things, and this is what I found :

forms["List_RETAIL_NOTIFICATION"] evaluates to "true,false" forms.GetValues("List_RETAIL_NOTIFICATION")[0] evaluates to "true" (forms.GetValue("List_RETAIL_NOTIFICATION").RawValue as string[])[0] evaluates to "true" forms.GetValues("List_RETAIL_NOTIFICATION").FirstOrDefault() evaluates to "true"

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about checkbox