在Angular中传递一个对象数组给POST

本文关键字:数组 POST 一个对象 Angular | 更新日期: 2023-09-27 18:02:06

我试图在Angular控制器中创建一个函数,该函数将TestExpense对象数组传递给c# 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<Expenses> expenses参数来模仿的功能。从我收集的,我需要反序列化JSON字符串,将代表我的$scope.TestExpenses数组,但我不确定如何开始解析出单独的Expense对象从它。

RouteConfig.cs中相关路由:

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

任何指导将不胜感激!

在Angular中传递一个对象数组给POST

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

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

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

从我收集的,我需要反序列化JSON字符串,将表示我的$scope。TestExpenses数组,但我不确定如何

没有

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

一个更好的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<T>

p。不要使用.success.error回调,因为它们已经过时了。使用.then

在angular 1中正确的post方式。X,使用$http是:

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