How do I bind a dictionary to a set of checkboxes using ASP.NET MVC?

南笙酒味 提交于 2019-12-04 11:45:05

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!