如何使用angularJs将数组对象传递给web api方法

时间:2016-07-22 12:35:11

标签: c# angularjs asp.net-web-api

我正在创建一个客户端脚本,使用$http将字典对象类型发送到web api方法,如下所示:

    $scope.SearchPolicyDetails = function (data) {
    var searchPolicy = new Array();
    searchPolicy["InsuredName"] = data.InsuredName;
    searchPolicy["PostalCode"] = data.PostalCode;
    searchPolicy["LOB"] = data.LOB;
    searchPolicy["AgencyName"] = data.AgencyName;
    searchPolicy["Symbol"] = data.Symbol;
    searchPolicy["PolicyNum"] = data.PolicyNum;
    searchPolicy["MCO"] = data.MCO;
    searchPolicy["expireswithin"] = data.expireswithin;
    searchPolicy["SortFields"] = data.SortFields;
    searchPolicy["SortOrder"] = data.SortOrder;

    $http({
        url: "http://localhost:53054/api/GetPoliciesBySearch",
        dataType: 'json',

        data: searchPolicy,
        headers: {
            "Content-Type": "application/json"
        }
    }).success(function (response) {
        $scope.value = response;
    })

};

我有WebAPI方法:

    public List<Dictionary<string,string>> GetPoliciesBySearch(Dictionary<string,string> policySearch)
    {

        return SpecializedHandler.GetAllPolicies(policySearch).IterativeResource;
    }

但我没有收到该方法的对象。

我在Chrome控制台中看到了这个错误:

enter image description here

4 个答案:

答案 0 :(得分:1)

我认为您的代码和UI在不同的项目中,可能您没有在web.config或WebApiConfig.cs中配置CORS。您可以关注此网址

https://msdn.microsoft.com/en-us/magazine/dn532203.aspx

答案 1 :(得分:0)

您需要定义一个类并使用它,而不是在API操作中使用字典。

class PolicyRequest 
{
     public string InsuredName { get; set; }
     public string PostalCode { get; set; }
     public string LOB { get; set; }
     ...
}

答案 2 :(得分:0)

searchPolicy [&#34; InsuredName&#34;] = searchPolicy.InsuredName。这不是一个数组,而是一个具有InsuredName等属性的json对象。使它成为一个数组。你可以做 : var searchPolicy = []; searchPolicy.push(data.InsuredName);

答案 3 :(得分:0)

看起来这里有很多事情需要考虑:

首先:客户端创建的对象不会转换为List<Dictionary<string, string>>,因此我们希望我们可以进行一些更改。考虑:

var searchPolicy = {};
searchPolicy['InsuredName'] = data.InsuredName;
searchPolicy['PostalCode'] = data.PostalCode;
//etc (see below for another crucial piece)    

第二:$http内部调用的代码并非针对任何特定方法(see the docs)。考虑一下以下内容:

$http({
    url: "http://localhost:53054/api/GetPoliciesBySearch",
    dataType: 'json',
    method: 'POST',
    data: JSON.stringify(searchPolicy),
    headers: {
        "Content-Type": "application/json"
    }
}).then(successHandler, errorHandler);

//try to avoid the deprecated success / error functions

function successHandler(response){
    $scope.value = response;
}

function errorHandler(response){
    //I strongly consider this for debugging
    console.log(response);
}

第三:考虑在WebAPI控制器中接受标准Dictionary<string, string>,因为新对象不应该是字典列表而是平面字典。 (this answer may provide more context

最后:看起来路由可能会因错误消息而混淆;确保WebApiConfig.cs中的路由设置类似于:

RouteTable.Routes.MapHttpRoute("GetPoliciesBySearch",
    "api/getpoliciesbysearch",
    defaults: new 
    {
        controller = "{your controller name here}", 
        action = "GetPoliciesBySearch"
    });