【问题标题】:How to Post multiple rows with AngularJS如何使用 AngularJS 发布多行
【发布时间】:2014-12-29 13:41:09
【问题描述】:

我正在尝试提交包含多个表格行的表单。我在网上找到了示例,并设法将表数据发送到 AngularJS 控制器,但我不知道如何将该数据发送到 apiController。

该表单是一个采购订单,其中包含一个包含采购订单详细信息的表格。我已将提交按钮与采购订单和采购订单详细信息提交功能链接起来。

<table class="table" style="">
    <tbody>
        <tr class="pointer no_selection" ng-repeat="newJobItem in rows">
            <td style="width:50px"><input style="width:20px" type="checkbox" class="form-control"></td>
            <td style="width:200px">{{newJobItem.JobItemName}}</td>
            <td style="width:480px">{{newJobItem.JobItemDescription}}</td>
            <td style="width:100px">{{newJobItem.JobItemMatSize}}</td>
            <td style="width:150px">{{newJobItem.JobItemQuantity}}</td>
            <td style="width:50px">{{newJobItem.JobItemUOM}}</td>
            <td style="width:150px">${{newJobItem.JobItemPrice | number : fractionSize}}</td>
            <td style="width:20px"><input type="button" value="X" class="btn btn-primary btn-sm" ng-click="removeRow(newJobItem.JobItemName)" /></td>
        </tr>

    </tbody>
</table>


<input style="margin-right:30px" id="btn-width" type="button" class="btn btn-default" ng-click="submitPurchaseOrder();submitPurchaseOrderDetail()" value="Submit"/>

控制器

   //Post Purchase Order
$scope.PODate = new Date(); //Todays Date
$scope.POId = Math.floor(Math.random() * 1000000001) //PurchaseOrder Id Generator
$scope.submitPurchaseOrder = function () {;
    var data = {
        JobId: $scope.job.JobId,
        POId : $scope.POId,
        PONumber: $scope.currentItem.PONumber,
        PODate: $scope.PODate,
        POAmount: $scope.currentItem.POAmount,
        POLastPrintDate: $scope.currentItem.POLastPrintDate,
        POEmail: $scope.POEmail,
        POPrint: $scope.currentItem.POPrint,
        POFaxNumber: $scope.POFaxNumber,
        PONotes: $scope.currentItem.PONotes,
        POCreatedBy: $scope.currentItem.POCreatedBy,
        PODeliveryDate: $scope.currentItem.PODeliveryDate,
        POShipVia: $scope.currentItem.POShipVia,
        POShowPrices: $scope.currentItem.POShowPrices,
        POCostCode: $scope.currentItem.POCostCode,
        POApprovedNumber: $scope.currentItem.POApprovedNumber,
        POBackorder: $scope.currentItem.POBackorder,
       }
    $http.post('/api/apiPurchaseOrder/PostNewPurchaseOrder', data).success(function (data, status, headers) {
        console.log(data);
        var tmpCurrentItem = angular.copy($scope.currentItem);
        $scope.purchaseOrderArray.push(tmpCurrentItem)
        angular.copy({}, $scope.currentItem);
        //hide modal window
        $scope.openNewPurchaseOrderModal.then(function (m) {
            m.modal('hide');
        });

    });
};
//Post Purchase Order Detail
$scope.newJobItem = {};
$scope.submitPurchaseOrderDetail = function () {
    var index = 0;
    $scope.rows.forEach(function (newJobItem) {
        console.log('rows #' + (index++) + ': ' + JSON.stringify(newJobItem));
    });
    var data = {
        POId: $scope.POId,
        PODItem: $scope.newJobItem.JobItemName,
        PODDescription: $scope.newJobItem.JobItemDescription,
        PODNotes: $scope.PODNotes,
        PODUOM: $scope.newJobItem.JobItemUOM,
        PODPrice: $scope.newJobItem.JobItemPrice,
        PODQuantity: $scope.newJobItem.JobItemQuantity,
        PODAmount: $scope.PODAmount,
        PODMatSize: $scope.newJobItem.JobItemMatSize,
        PODSection: $scope.PODSection,
        PODMultiplier: $scope.PODMultiplier,
        PODBackOrder: $scope.PODBackOrder
    }
    $http.post('/api/apiPurchaseOrderDetail/PostNewPurchaseOrderDetail', data).success(function (data, status, headers) {
        console.log(data); window.top.location.reload();

    });
};

采购订单明细ApiController

 // POST api/<controller>

    public async Task<IHttpActionResult> PostnewPurchaseOrderDetail([FromBody]PurchaseOrderDetail newPurchaseOrderDetail)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        using (var context = new ApplicationDbContext())
        {
            context.PurchaseOrderDetails.Add(newPurchaseOrderDetail);
            await context.SaveChangesAsync();
            return CreatedAtRoute("PurchaseOrderDetailApi", new { newPurchaseOrderDetail.PODId }, newPurchaseOrderDetail);
        }
    }

更新 已按建议更改

 // POST api/<controller>
    public HttpResponseMessage PostNewPurchaseOrderDetail(int id, PurchaseOrderDetail newPurchaseOrderDetail)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        if (!ModelState.IsValid)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }

        if (id != newPurchaseOrderDetail.PODId)
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        db.Entry(newPurchaseOrderDetail).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
        }

        return Request.CreateResponse(HttpStatusCode.OK);
    }

【问题讨论】:

    标签: javascript angularjs asp.net-web-api2 asp.net-mvc-5.1


    【解决方案1】:

    您正在执行两个函数,每个函数都发出一个异步请求:

    ng-click="submitPurchaseOrder();submitPurchaseOrderDetail()"
    

    这感觉不对 - 两个请求是并行发送的,没有一个在等待另一个。你是认真的吗?

    我会在一个请求中打包并发送所有数据(也为用户提供更好的体验),然后让服务器处理解包。或者,如果一个请求需要等待另一个请求,则链接$http 返回的Promises

    $http.post(...)
         .then(function(){
             return $http.post(...);
         })
         .success(...)
         .fail(...);
    

    或改用$q.all(promises)

    编辑。

    还有一种更简洁、更可扩展的方法是使用专用的 Angular Service 来发布您的数据,请参阅例如Angular Homepage上的示例

    【讨论】:

    • 我不知道该怎么做,但使用 Promise 是有意义的。但是还是不知道怎么把PurchaseOrderDetail数据发送给apiController?
    • 我在网上找到的唯一显示如何提交多条记录的示例是强类型项目。
    • @texas697 您的 ajax 请求看起来不错,您可以尝试 requestb.in 看看您的请求是如何到达的,然后单独测试您的 PHP 端点。那里有很多例子,寻找 Angular/PHP。
    【解决方案2】:

    我不确定您的方法,对我来说,最好将请求、purchaseOrder 和详细信息合并到一个调用中,您仍然可以根据自己的方便将数据分开。

    同时调用这两个函数可能会出现意外行为,因为它们都是异步运行的,您可能会发现“竞争条件”。

    尝试发送单个请求并组织您将如何发布信息,例如

    var data = {
        JobId: $scope.job.JobId, //common data between the order and the detail
        POId: $scope.POId,
        Order:{
    
            PONumber: $scope.currentItem.PONumber,
            PODate: $scope.PODate,
            POAmount: $scope.currentItem.POAmount,
            POLastPrintDate: $scope.currentItem.POLastPrintDate,
            POEmail: $scope.POEmail,
            POPrint: $scope.currentItem.POPrint,
            POFaxNumber: $scope.POFaxNumber,
            PONotes: $scope.currentItem.PONotes,
            POCreatedBy: $scope.currentItem.POCreatedBy,
            PODeliveryDate: $scope.currentItem.PODeliveryDate,
            POShipVia: $scope.currentItem.POShipVia,
            POShowPrices: $scope.currentItem.POShowPrices,
            POCostCode: $scope.currentItem.POCostCode,
            POApprovedNumber: $scope.currentItem.POApprovedNumber,
            POBackorder: $scope.currentItem.POBackorder,
        },
        Detail:{
            PODItem: $scope.newJobItem.JobItemName,
            PODDescription: $scope.newJobItem.JobItemDescription,
            PODNotes: $scope.PODNotes,
            PODUOM: $scope.newJobItem.JobItemUOM,
            PODPrice: $scope.newJobItem.JobItemPrice,
            PODQuantity: $scope.newJobItem.JobItemQuantity,
            PODAmount: $scope.PODAmount,
            PODMatSize: $scope.newJobItem.JobItemMatSize,
            PODSection: $scope.PODSection,
            PODMultiplier: $scope.PODMultiplier,
            PODBackOrder: $scope.PODBackOrder
        }
    
    }
    

    您需要将采购订单和详细信息映射到 api 控制器中的单个 dto 对象。

    作为旁注,我建议您使用stronger unique identifier 而不是随机数。

    【讨论】:

      【解决方案3】:

      我认为问题在于你的控制器尝试使用它,你能否详细说明问题。你的控制器永远找不到你的 APIcontroller 吗?

      public class Oders : ApiController // in your controller class
      {
       public HttpResponseMessage Post(PurchaseOrderDetails newOrder)
       {
       //your code
       }
      
      }
      

      【讨论】:

      • 好的,我将 apiController 修改为 HttpResponseMessage 而不是异步。但我仍然需要设置 Angular 控制器以发送回数据和“行”。现在它没有这样做。我不知道如何结合2
      • 但我很好奇你为什么建议我将异步更改为 HttpResponse?
      • 我在尝试添加多个条目时使用相同的东西,并且我的控制器发出 http 请求 $http.post('/api/nameofcontroller/',this.newOrder).success.. .
      • 你在前端使用 Angular 吗?我需要先进行设置,这样我才能看到控制器中发生了什么
      • 是的,我正在使用 angular...但我以为您之前说过您正在控制器中获取数据,唯一的问题是 APIcontroller ?
      猜你喜欢
      • 2018-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      相关资源
      最近更新 更多