如何绑定字典一组使用ASP.NET MVC复选框? [英] How do I bind a dictionary to a set of checkboxes using 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有一个名为的字符串属性名称
从中你会得到复选框的名称。请注意,我已经改变了这preface它的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,但你也可以尝试模型$ P $ PFIXMyType的直接到词典&LT结合,字符串,布尔&GT;
,然后翻译。
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;
}
...
}
您还可以,对客户端一点的javascript,在提交之前添加名称=关闭
为每一个未复选框的参数,这将消除需要填写原始字典,因为你就可以直接推导出所有的字典元素的值。
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屋!