Angular JS MVC Web API Model/ Parameter not binding .NET Core

前端 未结 3 1249
执念已碎
执念已碎 2021-01-12 17:08

I am using Angular JS with TypeScript and ASP.NET Core MVC/API.

I have an apiService which deals with all POST and GET reques

3条回答
  •  感情败类
    2021-01-12 17:26

    Its always better to do a GET instead of POST for get requests. If you would like to change it to a GET method, then make $http.get and in api attribute, have it like:

        [HttpGet] //not required, this will be get as per naming convention
        [Route("GetAssetListByCompany/{companyId}")]
        public IActionResult GetAssetListByCompany(int companyId)
    

    But if you still need to do a POST, then your data in $http.post should look like data: '"123456"'

    $http.post("/api/Dashboard/GetAssetListByCompany", '"123456"' )
    

    The above workaround is needed when you pass primitive data to api and that explains why it worked fine when you passed your viewmodel.

    UPDATE: After further discussion, OP needs to POST multiple primitive types to api and need to access the data using a key without having dependency with the order in which the model is being bind.

    One option is to use Dictionary as input param type

     [HttpPost]
     [Route("GetAssetListByCompany")]
     public IHttpActionResult GetAssetListByCompany(Dictionary data)
            {
                return Ok();
            }
    

    and in client side:

        var data = {};
        data["CustomerId1"] = 123;
        data["CustomerId2"] = 345;
        data["CustomerId3"] = 1623;
        data["CustomerId4"] = 7655;
    
        $http.post("/api/Dashboard/GetAssetListByCompany", data);
    

    Result

提交回复
热议问题