angularjs 从AngualrJS向Web API发送对象数组

jjjwad0x  于 2022-12-17  发布在  Angular
关注(0)|答案(3)|浏览(126)

在这个过程中,我从API中获取一个“车辆”数组,对每个车辆进行修改和操作,然后将列表发送回去,而不需要遍历和循环...
我已经尝试了很多方法,我已经在WEB API中找到了一个断点,看看我是否可以在那里得到数组,但是我还没有做到。

public IHttpActionResult UpdateVehicles(Vehicle[] vehiclesArry)
    {
        return Ok();
    }

我很困惑我是否需要做一个$post,或者我是否可以像我一直在做的那样把它“得到”到正确的方法。问题是我不能把数组得到API方法。
我的$resource设置如下所示。

return $resource(appSettings.serverPath + "/api/Violators/:id",null,
         {
             'update': { method: 'PUT' },
             'delete': { method: 'DELETE' },
             'post': { method: 'POST' }
         });

我试过使用$post,但是它说对象不支持它。我不确定我还能尝试什么其他方法。我试过在web API中使用“dynamic”,似乎也不起作用。

x6h2sr28

x6h2sr281#

您缺少$resource的params对象,因此它不知道id。

return $resource(appSettings.serverPath + "/api/Violators/:id", { id: '@id' });

你不需要显式地设置get,post,delete的方法。这些已经为你做好了。如果你的API使用PUT来更新,就像这样设置:

return $resource(appSettings.serverPath + "/api/Violators/:id", { id: '@id' }, {
   update: { method: 'PUT' }
});

另外,资源的属性必须是vehiclesArry,否则web API不知道如何Map它。我还想回显@sowen。您需要设置端点接收的视图模型。

yzuktlbb

yzuktlbb2#

我的假设是您的页面中有一些脚本错误,或者您没有正确使用$http方法。
人们经常遇到的一个问题是使用正确的url到你的angular控制器的web API端点。如果你没有正确的使用它,你可能会得到404错误。在你的浏览器控制台(网络标签)中查找这些错误。
下面的代码应该可以正常工作,没有任何问题

$http.get("../api/Values/")
    .then(function (res) {

        var vehicles = res.data;
        console.log('data received', JSON.stringify(vehicles));

        //Let's update the Name of each vehicle.
        $.each(vehicles, function (indx, item) {
            item.Name = item.Name + " Updated";
        });

        console.log('data modified', JSON.stringify(vehicles));

        //Let's make a call to web api with modified data
        $http.post("../api/Values/UpdateVehicles", vehicles)
            .then(function (res2) {
                console.log('response', JSON.stringify(res2.data));
            });

    });

假设你已经在页面中正确加载了angular js,上面的代码是当前页面的angular控制器的一部分,并且你有一个带有2个动作方法的Web API控制器,如下所示。

public class ValuesController : ApiController
{
    [HttpPost]
    [Route("api/Values/UpdateVehicles")]
    public IHttpActionResult UpdateVehicles(Vehicle[] vehiclesArry)
    {
        // just returning whatever came in for TESTING PURPOSE
        return Ok(vehiclesArry);
    }
    public IEnumerable<Vehicle> Get()
    {
        return new List<Vehicle>
        {
             new Vehicle {Id = 1, Name = "Car"},
             new Vehicle {Id = 2, Name = "Van"}
        };
     }
}

另外,仅供参考:我在UpdateVehicle端点的API控制器中使用Attribute routing

ebdffaop

ebdffaop3#

创建模型对象,如

public class UpdateReq  
{
    public IEnumerable<Vehicle> Vehicles { get; set; }
}

从您的Angular ,只需传递一个带有数组的json

{
   [v1, v2, v3]
}

相关问题