Javascript数组作为WCF Web服务参数 [英] Javascript Array as WCF Webservice Parameter

查看:175
本文介绍了Javascript数组作为WCF Web服务参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个简单的Javascript数组传递给我的wcf ajax webservice:

I need to pass a simple Javascript array to my wcf ajax webservice:

var array = new Array();
array["ParamA"] = "xyz";
array["12344"] = "9";
myNamespace.DoSomething(array);

这是我的WCF方法:

[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public void DoSomething(object values)

当使用我的值从javascript调用时,values是一个空数组。
将一个简单的KeyValuePairs列表传递给我的webservice的最佳方法是什么?

"values" is an empty array when it is called from javascript with my values. What is the best approach to pass a simple list of KeyValuePairs to my webservice?

推荐答案

我能找到解决方案我自己:

I was able to find the solution myself:

[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public void DoSomething(Dictionary<string, object> values)

必须在像这样的javascript:

must be called in javascript like this:

var params = [{Key:A,Value:5},{Key:B,Value :测试}]

var params = [{ "Key": "A", "Value": 5}, { "Key": "B", "Value": "Test}]

$.ajax({
    type: "POST",
    contentType: "application/json",
    dataType: "json",
    data: '{"values":' + JSON.stringify(params) + '}',
    ...

这当然可以简化:

var parameters = [{ "A": 5}, { "B": "Test"}];

var dictionary = new Array();
for (var i in parameters) {
   var key = Object.keys(args[i])[0];
   var value = args[i][key];
   dictionary.push({ "Key": key, "Value": value });
} 

$.ajax({
    type: "POST",
    contentType: "application/json",
    dataType: "json",
    data: '{"values":' + JSON.stringify(dictionary) + '}',
    ...

这篇关于Javascript数组作为WCF Web服务参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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