从jQuery-MVC 2调用支持AJAX的WCF服务

时间:2010-12-21 19:37:21

标签: asp.net-mvc-2 jquery wcf

我已经完成了大量阅读,看起来非常简单。我创建了我的服务,这非常简单(看起来像这样

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WeddingPhotographerService
{    
    // Add more operations here and mark them with [OperationContract]
    [OperationContract]
    public bool AddNewSkill(string name, string description)
    {
        IRepository<Skill> skillRepo = ObjectFactory.GetInstance<IRepository<Skill>>();

        var skill = new Skill { Name = name, Description = description };
        skillRepo.Save(skill);
        return true;
    }
}

很简单,然后我在我的视图中写了这个jQuery代码

$(document).ready(function () {
    $("#AddSkill").click(function () {
        var data = { name: $("#NewSkill").val(), description: "" };
        data = JSON.stringify(data)
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WeddingPhotographerService.svc/AddNewSkill",
            data: data,
            dataType: "json",
            success: function () {
                $('#SkillListViewContainer').load('../AccountController/GetSkillControl');
            },
            error: function (msg) {
                $("#AddSkillError").text(msg.d);
            }
        });
    });
});

我的 WeddingPhotographerService.svc 位于项目的根目录中,当我创建服务时,web.config添加了这个

<system.serviceModel>
  <behaviors>
    <endpointBehaviors>
      <behavior name="WeddingPhotographer.WeddingPhotographerServiceAspNetAjaxBehavior">
        <enableWebScript />
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <services>
    <service name="WeddingPhotographer.WeddingPhotographerService">
      <endpoint address="" behaviorConfiguration="WeddingPhotographer.WeddingPhotographerServiceAspNetAjaxBehavior"
        binding="webHttpBinding" contract="WeddingPhotographer.WeddingPhotographerService" />
    </service>
  </services>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
    multipleSiteBindingsEnabled="true" />
</system.serviceModel>

一切看起来都很简单并且看起来它应该可以工作但是当我点击 AddSkill Chrome JavaScript控制台时会返回404错误,所以它根本找不到服务(因为我打开了控制台,因为当我点击按钮时,什么都没发生。

我在这里错过了什么吗?

顺便说一句,我也试过了(因为那是 web.config 文件中的名字)

url: "WeddingPhotographer.WeddingPhotographerService.svc/AddNewSkill"

我仍然收到资源未找到(404)错误

1 个答案:

答案 0 :(得分:4)

解决了它,将jQuery AJAX调用中的 url 行改为

url: "../WeddingPhotographerService.svc/AddNewSkill"

一切都很好