将对象从Angular Post传递到.Net ASMX

时间:2015-11-03 17:26:27

标签: json angularjs c#-4.0 asmx

我一直在尝试将对象作为Post参数传递给.NET asmx Web服务。我可以传递原始类型,如int,string作为参数,但我想传递整个对象,因为我的类包含很多属性,单独传递每个属性非常耗时。

我的c#网络服务代码是:

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ContactBLL AddContact(ContactBLL Contact)
{
   //add contact and return the contact object
}

我在Web服务类的顶部添加了以下语句:

[System.Web.Script.Services.ScriptService]

我在Web服务中有第二个函数,我在页面加载时调用它以获取json ContactBLL对象。

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ContactBLL GetContact(int ContactID)
{
    //return contact
}

我在工厂中使用以下函数来调用asmx web方法:



factory.GetContactInfo = function (ContactID) {    
    return $http.post(serviceBase + 'GetContact', { ContactID: ContactID }).then(function (results) {
        return results.data;
    });
};

factory.InsertContact = function (Contact) {
    return $http.post(serviceBase + 'AddContact', { ContactBLL: Contact }).then(function (results) {                
        return results.data;
    });
};




在我的控制器中,当页面加载时调用GetContact函数,它返回正确的数据以初始化Contact对象。然后我调用AddContact函数并将对象传递给工厂函数。控件无法访问Web服务,我在chrome中看到500消息,并显示以下消息: 消息:"无效的Web服务呼叫,缺少参数值:'联系'。"

以下是控制器的代码:



var ContactController = function ($scope, $location, $http, $window, ContactService) {
    var Contact;
    Initialise();
    function Initialise() {
        Contact = {};
        GetContact(-1);
    }

    function GetContact(ContactID) {
        ContactService.GetContactInfo(ContactID)
        .then(function (data) {
            //do something
        }, function (error) {
            $window.alert('Sorry, an error occurred: ' + error.data.message);
        });
    }

    $scope.AddContactRecord = function () {
        ContactService.InsertContact(Contact)
        .then(function (data) {
            //do something
        }, function (error) {
            $window.alert('Sorry, an error occurred: ' + error.data.message);
        });
    }
}




如果我做错了什么或通过邮局通过几十个属性的简单方法,请告诉我。 GetContact调用工作正常,但是,我在InsertContact调用时遇到错误。

1 个答案:

答案 0 :(得分:0)

我找到了错误的原因。我传递的数据类型(ContactBLL)而不是我工厂的AddContact函数中参数的名称(Contact)。正确的代码如下:



factory.InsertContact = function (Contact) {
    return $http.post(serviceBase + 'AddContact', { Contact: Contact }).then(function (results) {                
        return results.data;
    });
};