2

我创建了简单的 WCF 服务并将其添加到 ASP.NET MVC 应用程序中。

该服务有一个方法RepeatString:

[OperationContract]
public string RepeatString(string s, int times)
{
   string result = "";

   for (int i = 0; i < times; ++i)
   {
       result += s;
   }


   return result;
}

我尝试使用 post 和 get 方法从视图 (.cshtml) 调用此方法:

function callAjaxService1() {    
    $.post("~/AjaxService1.svc/RepeatString", {s : 'Test', times : 12},
        function(data) {
            alert('data from service');
        }, 'json');
}

function callAjaxService1() {    
    $.get("~/AjaxService1.svc/RepeatString", {s : 'Test', times : 12},
        function(data) {
            alert('data from service');
        }, 'json');
}

但两者都没有成功。

在 WCF 服务操作装饰中我应该改变什么还是我错误地使用了 jQuery.get/post?

4

2 回答 2

1

我会想到这样的事情......

wcf接口服务

[OperationContract]
[WebGet(UriTemplate = "/repeatstring",
ResponseFormat= WebMessageFormat.Json)]
string RepeatString(string s, int times);

然后你的代码

public string RepeatString(string s, int times)
{
   string result = "";

   for (int i = 0; i < times; ++i)
   {
       result += s;
   }


   return result;
}

没有 operationcontract 但页面将从接口派生,因此您的 ajax 代码将是这样的。

$.ajax({
  type: "GET", //to get your data from the wcf service
  url: "AjaxService1.svc/repeatstring", //you might need to add the hostname at the beginning too
  data: option // or { propertyname1: "John", propertyname2: "Boston" }
})
  .done(function() {
    alert( "got data" );
  });

您可以向 $.ajax 添加更多选项。您可以将“完成”承诺更改为“成功”,这将在操作成功时起作用。当我创建我的 wcf 服务并需要发送数据至 json 并使用 javascript 获取它时,我使用了成功。无论如何,您可以在此处阅读有关它的更多信息

在编写 json 字符串或“option”变量时,请注意单引号 ' 和双引号

现在我希望这能以某种方式帮助你。干杯

于 2013-12-14T21:47:32.740 回答
0

从 javascript 调用 WCF 需要注意三件事。

  1. 服务必须用 WebInvoke/WebGet 修饰才能从 javascript 访问。

  2. <enableWebScript/>必须添加到配置中以启用对 WCF 的脚本调用。

  3. webHttpBinding 将用于 WCF 以充当 REST 服务。

于 2013-12-14T21:16:58.277 回答