使用javascript的动态字典
我试图在客户端填充字典对象,我可以传递给我的Action方法。 我能够使用硬编码值构建字典对象,但是我想基于DOM元素动态创建它。
以下是如何编写代码:
这是具有硬编码值的JavaScript函数。 我正在遍历所有具有textClass
的文本框。 这工作正常,我能够在Action方法参数中看到字典项。
$('.textClass').each(function (index) { dictionary = { '[0].Key': 'k1', '[0].Value': 'v1', };
这是我想要构建字典的方式,但我无法弄清楚如何使用索引和DOM元素来创建字典键和值。 如果我按照下面的方式编写,它不构造字典。
$('.textClass').each(function (index) { dictionary = { '[' + index '].Key': $(this).attr('id'), '[' + index '].Value': $(this).val(), };
有人可以指点我在这里做错了什么吗?
为了能够从字符串构造键,您需要相应地设置它们:
var dictionary = {}; dictionary['[' + index + '].Key'] = $(this).attr('id');
您当前正在为每次迭代覆盖字典变量。 在您的场景中,您需要以下内容:
var dictionary = {}; $('.textClass').each(function (index) { dictionary['['+index+'].Key'] = $(this).attr('id'); dictionary['['+index+'].Value'] = $(this).val(); });
$('.textClass').each(function(index) { dictionary = {}; dictionary['[' + index + '].Key'] = $(this).attr('id'); dictionary['[' + index + '].Value'] = $(this).val(); });
- 动态添加字段的客户端validation
- 麻烦模型将JSON数组绑定到ASP.NET MVC 3中的List?
- 加载ASP.Net MVC JSONResult jQuery DataTables
- 从控制器返回Json,从未成功
- .NET MVC3中的JSON:500(内部服务器服务器错误)
- asp.net mvc 3如何在dropdownlist上使用jquery change事件来使用Controller中的ActionResult填充另一个下拉列表
- JQuery用DropDownList替换文本框
- 处理ajax中的会话超时
- 如果使用jqueryvalidation发生validation错误,则将类添加到父div