如何使用ASP.NET MVC将字典绑定到一组复选框? [英] How do I bind a dictionary to a set of checkboxes using ASP.NET MVC?

查看:398
本文介绍了如何使用ASP.NET MVC将字典绑定到一组复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的需要是绑定

Dictionary<MyType, bool> 

列出在asp.net mvc中的复选框。

to list of checkboxes in asp.net mvc.

我对如何实现这一点感到困惑。有人可以帮助我吗?

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

推荐答案

假设MyType有一个字符串属性,名为 Name 您将从中获取复选框的名称。请注意,我已将其更改为 MyType 的前言,所以我们可以在服务器上轻松区分它。如果您有其他方式可以确定哪些字段是复选框,则可能不需要此步骤。

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 ) %>
<% } %>

控制器(这使用FormParameters,但您也可以直接尝试使用前缀MyType的模型绑定字典< string,bool> ,然后翻译。

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;
    }

    ...
}

你也可以用ab它在客户端的javascript,在提交之前为每个未选中复选框添加 name = off 参数,这样可以避免您填写原始字典可以直接导出所有字典元素的值。

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.

这篇关于如何使用ASP.NET MVC将字典绑定到一组复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆