问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/962189/how-do-i-bind-a-dictionary-to-a-set-of-checkboxes-using-asp-net-mvc