【问题标题】:Pass array of objects to POST in Angular将对象数组传递给 Angular 中的 POST
【发布时间】:2016-08-12 15:29:06
【问题描述】:

我正在尝试在 Angular 控制器中创建一个函数,该函数将 TestExpense 对象数组传递给 C# API,然后该 API 将处理将它们插入数据库。目前,API 仅配置为一次执行一项。

我希望传递的数组对象$scope.TestExpenses由以下构造函数表示:

function TestExpense(employeeId, expenseDate, taskId, expenseTypeId,
    billingCategory, notes, amount, lastUpdatedDate, lastUpdatedBy, dateSubmitted) {
    this.employeeId = employeeId;
    this.expenseDate = expenseDate;
    this.taskId = taskId;
    this.expenseTypeId = expenseTypeId;
    this.billingCategory = billingCategory;
    this.notes = notes;
    this.amount = amount;
    this.lastUpdatedDate = lastUpdatedDate;
    this.lastUpdatedBy = lastUpdatedBy;
    this.dateSubmitted = dateSubmitted;
    this.location = location;
}

$scope.TestExpenses = [];

相关Angular函数submitEntriesToDatabase的当前状态:

$scope.submitEntriesToDatabase = function () {
    $http.post('/expense/submitExpense', $scope.TestExpenses)
    .success(function (data, status, headers, config) {

    })
    .error(function (data, status, headers, config) {

    });


};

在 C# 中,我有以下模型来对应我的 TestExpense 对象:

public class Expense
{
    public int employeeId { get; set; }
    public string expenseDate { get; set; }
    public int taskId { get; set; }
    public int expenseTypeId { get; set; }
    public int billingCategory { get; set; }
    public string notes { get; set; }
    public float amount { get; set; }
    public string LastUpdatedDate { get; set; }
    public int LastUpdatedBy { get; set; }
    public string dateSubmitted { get; set; }
    public string location { get; set; }
}

以及API中处理POST的方法:

    public void SubmitExpenses(List<Expense> expenses)
    {

        //using(cnxn)
        //{
        //    using(SqlCommand sqlQuery = new SqlCommand("INSERT INTO Expenses " + 
        //        "(Employee_ID, Task_ID, Expense_Date, Expense_Type_ID, Billing_Category_ID, " + 
        //        "Amount, Notes, Last_Updated_By, Last_Update_Datetime, Date_Submitted, Location) " +
        //        "Values (@employeeId, @taskId, @expenseDate, @expenseTypeId, @billingCategory, @amount, @notes, " +
        //        "@lastUpdatedBy, @lastUpdatedDate, @dateSubmitted, @locationId)", cnxn))
        //    {
        //        sqlQuery.Parameters.Add(new SqlParameter("@employeeId", SqlDbType.Int) { Value = employeeId });
        //        sqlQuery.Parameters.Add(new SqlParameter("@expenseDate", SqlDbType.DateTime) { Value = expenseDate });
        //        sqlQuery.Parameters.Add(new SqlParameter("@taskId", SqlDbType.Int) { Value = taskId });
        //        sqlQuery.Parameters.Add(new SqlParameter("@expenseTypeId", SqlDbType.Int) { Value = expenseTypeId });
        //        sqlQuery.Parameters.Add(new SqlParameter("@billingCategory", SqlDbType.Int) { Value = billingCategory });
        //        sqlQuery.Parameters.Add(new SqlParameter("@notes", SqlDbType.Text) { Value = notes });
        //        sqlQuery.Parameters.Add(new SqlParameter("@amount", SqlDbType.Money) { Value = amount });
        //        sqlQuery.Parameters.Add(new SqlParameter("@lastUpdatedDate", SqlDbType.DateTime) { Value = lastUpdatedDate });
        //        sqlQuery.Parameters.Add(new SqlParameter("@lastUpdatedBy", SqlDbType.Int) { Value = lastUpdatedBy });
        //        sqlQuery.Parameters.Add(new SqlParameter("@dateSubmitted", SqlDbType.DateTime) { Value = dateSubmitted });
        //        sqlQuery.Parameters.Add(new SqlParameter("@locationId", SqlDbType.VarChar) { Value = "Radnor" });


        //        cnxn.Open();
        //        sqlQuery.ExecuteNonQuery();
        //    }
        //}



    }

SubmitExpenses 中注释掉的行用于插入单个条目(具有适当的方法签名,而不是现在的内容)。这也是我希望通过传递给它的List&lt;Expenses&gt; expenses 参数来模仿的功能。根据我收集到的信息,我需要反序列化代表我的 $scope.TestExpenses 数组的 JSON 字符串,但我不确定如何开始从中解析出单个 Expense 对象。

RouteConfig.cs中的相关路由:

routes.MapRoute(
     name:"SubmitExpense",
     url:"expense/submitExpense",
     defaults: new
     {
           controller = "Expense",
           action = "SubmitExpenses"
     }
);

任何指导将不胜感激!

【问题讨论】:

  • 设置的路由是什么,这个函数是怎么应用的?
  • $http.post 中所见。我知道数据被传递给我的控制器中的SubmitExpenses 方法,但我不知道如何分解作为参数传递的List,我觉得这是一个独立于路由的问题。
  • 我编辑了帖子,因为我没有正确缩进 SubmitClasses 方法标题。对不起。
  • 请说明SubmitExpenses 函数是如何在您的服务器上调用的。
  • 路由已发布,但我并不真正了解它的相关性,因为我知道应用程序和 API 已连接。从字面上看,只是更改了方法头,与路由无关。

标签: javascript c# angularjs arrays json


【解决方案1】:

根据我收集到的信息,我需要反序列化代表我的 $scope.TestExpenses 数组的 JSON 字符串,但我不确定如何开始从中解析出单个 Expense 对象。

简单。在您的方法签名中使用 [FromBody] 装饰器。您为所有控制器设置的默认 JSON 序列化程序设置将尝试将字符串解析到 Expense 列表中 - 如果您使用的是 Json.NET,它可以自动处理。

public void SubmitExpenses([FromBody] List<Expense> expenses)

【讨论】:

  • 我现在就试试这个。所以我应该能够通过索引从expenses 参数中访问一个元素作为Expense 对象,然后访问每个单独元素的属性?
  • +1 为您提供帮助,@toadflakz。正如@naveen 所详述的那样,我实际上并不需要[FromBody],但我很感激你帮助我走上了正确的道路。
  • 他是对的。只是 web api 使用 JSON.NET +1
【解决方案2】:

根据我收集到的信息,我需要反序列化 JSON 字符串 代表我的 $scope.TestExpenses 数组,但我不确定如何 开始从中解析出单个 Expense 对象。

。你不需要做任何事情来反序列化。它将被自动反序列化。

一个更好的 POST 请求实现是这样的。

$scope.submitEntriesToDatabase = function() {
    var config = {
        method: "POST",
        url: '/expense/submitExpense',
        data: $scope.TestExpenses
    };
    $http(config).then(function(response) {
        //success
    }, function(response) {
        //error
    });
};

如果数组中的属性名与你的泛型列表中的对象的属性名相同,web api会自动将javascript数组转换为List&lt;T&gt;

P.S:不要使用 .success.error 回调,因为它们已过时。使用.then

【讨论】:

  • 非常感谢!另外,+1 让我深入了解 $http.post 的正确用法
  • $http.post 同样不错。 $http 给了我们更多的控制权。在我看来它也更具可读性
【解决方案3】:

在 Angular 1.x 中使用 $http 发帖的正确方法是:

$http.post('/my/url',{foo:bar}).then(function(result) {
     console.log(result.data);  // data property on result contains your data
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 2020-07-12
    • 2019-12-19
    • 2017-07-21
    • 2015-05-30
    • 1970-01-01
    相关资源
    最近更新 更多