如何将参数传递给AngularJS资源?

时间:2015-12-17 09:27:25

标签: asp.net angularjs

我有一个ASP.NET应用程序,其形式由AngularJS处理。有2个日期时间选择器(fromDate和toDate变量)和复选框,指示是否包含开放日期(isOpenDatesIncluded)。

代码如下:

1)在第一个AngularJS模块中:

SearchActionsApp.controller("ListController", function($scope, $location,$q, Actions, ActionDates, CounterAgents,Counteragents, AsyncTask) {
...

$scope.actionsQuery = {
    searchText: "",
    fromDate: new Date(moment().format("MM/DD/YYYY")),
    toDate: new Date(moment().add('d', 3).format("MM/DD/YYYY")),
    isOpenDatesIncluded: false,
...

ActionDates.query({ actionId: action.Id }, task.success, task.error);

...

}

2)在service.js中:

.factory('ActionDates', function ($resource) {
    return $resource('/RestApi/api/ActionDates', {});
})

3)在服务器端:

public IEnumerable<ActionDateItem> QueryActionDates(ActionDateQuery query)
{
    var sql = query.BuildSql();
    using (var cn = CreateSqlConnection())
    {
        return cn.Query<ActionDateItem>(sql, new
        {
            query.ActionId,
            query.IsOpenDatesIncluded,
            BeginDate = query.FromDate,
            EndDate = query.ToDate
        });
    }
}

public class ActionDateQuery
{
    public ActionDateQuery()
    {
        ActionId = -1;
        IsOpenDatesIncluded = false;
        FromDate = new DateTime(1980, 1, 1);
        ToDate = DateTime.Now.AddYears(1);
    }

    public long ActionId { get; set; }
    public bool IsOpenDatesIncluded { get; set; }
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }
}

问题是查询返回的数据集从:1980,1,1到DateTime.Now.AddYears(1),但我需要返回范围内的数据:fromDate - toDate,我从客户端获取侧。除了action.Id之外,我还需要传递3个参数:fromDate,toDate和isOpenDatesIncluded。

怎么做?

2 个答案:

答案 0 :(得分:0)

只需将它们添加到query方法的参数中,如下所示:

query({
    actionId: action.Id,
    fromDate: $scope.actionsQuery.fromDate,
    ...
}, task.success, task.error)

如果它们未在资源中预先绑定,它们将作为查询参数附加到请求URL。

- 编辑 -

我也可以建议使用promises而不是回调,因为它有助于提高可读性和链接:

query({
    actionId: action.Id,
    fromDate: $scope.actionsQuery.fromDate,
    ...
}).$promise.then(function(response) {
    // success
}).catch(function(error) {
    // error
});

答案 1 :(得分:0)

    ActionDates.query({ actionId: action.Id }, task.success, task.error);

添加缺少的3个参数,例如         {actionId:action.Id,fromDate:fromDate,etc} 并尝试绑定资源中的参数         $ resource(&#39; / RestApi / api / ActionDates&#39;,{id:&#39; @ id&#39;,fromdate:&#39; @ fromdate&#39;,etc});