是否可以将字典发布到.NET MVC操作? [英] Is POSTing a Dictionary to an .NET MVC action possible?

查看:38
本文介绍了是否可以将字典发布到.NET MVC操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一系列字段的表格,

<input type="text" name="User[123]" value="Alice" />
<input type="text" name="User[456]" value="Bob" />
...

其中,用户数组的索引(123和456)是与值关联的ID.我正在尝试更新控制器中的这些值. 我的想法是,将ID映射到名称的Dictionary可以工作,但是可以创建以下操作:

public void Save(Dictionary<string, string> user) {
    // ...
}

导致用户参数为空.

那么,可以通过字典吗?或者,还有另一种方法可以实现这一目标吗?

解决方案

列表是可能的,我确信它也可以保留在字典中.通读绑定到列表的模型 Phil Haack撰写的文章,对列表绑定的工作原理有一些了解.

您应该能够做到这一点:

<input type="hidden" name="User.Index" value="123" />
<input type="text" name="User[123]" value="Alice" />

<input type="hidden" name="User.Index" value="456" />
<input type="text" name="User[456]" value="Bob" />

I have a form which contains a series of fields like:

<input type="text" name="User[123]" value="Alice" />
<input type="text" name="User[456]" value="Bob" />
...

Where the index of the User array (123 and 456) are ID's associated with the value. I'm trying to update these values in the controller. My thinking is that a Dictionary that maps ID to name would work, but creating the action like:

public void Save(Dictionary<string, string> user) {
    // ...
}

results in the user parameter being null.

So, is passing a Dictionary possible? or, is there another method to achieve this?

解决方案

It's possible for lists, I'm sure it carries over for dictionaries as well. Read through Model Binding to a List by Phil Haack for some understanding on how list binding works.

You should be able to do this:

<input type="hidden" name="User.Index" value="123" />
<input type="text" name="User[123]" value="Alice" />

<input type="hidden" name="User.Index" value="456" />
<input type="text" name="User[456]" value="Bob" />

这篇关于是否可以将字典发布到.NET MVC操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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