views:

1468

answers:

1

My need is to 'bind'

Dictionary<MyType, bool>

to list of checkboxes in asp.net mvc.

I'm confused about how to accomplish that. Could anyone help me?

+2  A: 

Assuming that MyType has a string property named Name from which you will get the name of the checkbox. Note that I've changed this to preface it with MyType so we can easily distinguish it on the server. You may not need this step if you have another way to determine which fields are the checkboxes.

<% foreach (var pair in model.ChecboxDictionary) { %>
   <%= Html.CheckBox( "MyType." + pair.Key.Name, pair.Value ) %>
<% } %>

Controller (this uses FormParameters, but you could also try model binding with prefix "MyType" directly to a Dictionary<string,bool>, then translate.

public ActionResult MyAction( FormParameters form )
{
    var dict = ... fill dictionary with original values...
    foreach (var key in dict.Keys)
    {
        if (!form.Keys.Contains( "MyType." + key.Name ))
        {
            dict[key] = false;
        }
    }

    foreach (var key in form.Keys.Where( k => k.StartsWith("MyType.")))
    {
        var value = form[key].Contains("on"); // just to be safe
        // create or retrieve the MyType object that goes with the key
        var myType = dict.Keys.Where( k => k.Name == key ).Single();

        dict[myType] = value;
    }

    ...
}

You could also, with a bit of javascript on the client-side, add name=off parameters for each of the "unchecked" checkboxes before submitting and that would obviate the need to fill the original dictionary since you'll be able to directly derive the values for all of the dictionary elements.

tvanfosson
So far i know too. Now i need to pass that data (with changed bool values) back to controller. Does your approach works for that and i`m just doing something wrong or it doesn't include that part?
Arnis L.
I see. I'll update my answer with one idea.
tvanfosson
And that's the question - how to make model binding to work. Sorry for my vagueness.
Arnis L.
This might help: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Arnis L.
Looks like i won't runaway from creating custom model binder.
Arnis L.
Dictionary<TEntity, bool> would demand repopulating data from repository to fill TEntity anyway. MyType can have a lot of props. But calling database for each dictionary entry form->server binding would be unacceptable. I guess i need to look somewhere else.
Arnis L.
You might look at caching them server side (if you're using LINQ they'll need to be serialized to detach/reattach them to the data context). Then you'd only need the key to do a simple look up. You might also want to consider a stripped down entity (view) if you are only updating a single property.
tvanfosson