【问题标题】:Passing an Object from Angular Post to .Net ASMX将对象从 Angular Post 传递到 .Net ASMX
【发布时间】:2015-11-03 17:26:27
【问题描述】:

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

我的 c# web 服务代码是:

[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 服务调用,参数缺失值:'Contact'。”

这是控制器的代码:

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);
        });
    }
}

如果我做错了什么或通过 Post 调用传递数十个属性的简单方法,请告诉我。 GetContact 调用工作正常,但是在 InsertContact 调用时出现错误。

【问题讨论】:

    标签: json angularjs c#-4.0 asmx


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多