I am using Angular JS with TypeScript and ASP.NET Core MVC/API.
I have an apiService
which deals with all POST
and GET
requests to the server, which looks like this:
module TBApp {
export class apiService {
static $inject = ['$http', 'notificationService'];
constructor(private $http, private notificationService: notificationService) {
}
get(url, config, success, failure) {
return this.$http.get(url, config)
.then(result => { this.handleResponse(result, success); }, result => { this.handleError(result, failure) });
}
post(url, data, success, failure) {
return this.$http.post(url,data)
.then(result => { this.handleResponse(result, success); }, result => { this.handleError(result, failure) });
}
handleResponse(result, success) {
alert('success');
success(result);
}
handleError(result, failure) {
if (result.status === '401') {
this.notificationService.displayError('Authentication required.');
//this.$rootScope.previousState = this.$location.path();
//this.$location.path('/login');
}
else if (failure !== null) {
failure(result);
}
}
}
}
Now when I send this request:
onCompanyChanged(selectedCompany, model, companyName) {
this.apiService.post('/api/Dashboard/GetAssetListByCompany', { companyId: selectedCompany.id },
response => {
this.assetListViewModel = response.data.data;
}, response => {
this.notificationService.displayError(response.data.message);
});
}
It is not binding the companyId
in the controller
Here is the controller:
[Route("api/[controller]")]
public class DashboardController : BaseController
{
[HttpPost]
[Route("GetAssetListByCompany")]
public IActionResult GetAssetListByCompany([FromBody]int companyId)
{
return CreateJsonResult(() =>
{
if (companyId == 0) { return new xPTJsonResult(null, xPTStatusCodesEnum.Success, "Company Id is 0"); }
//var treeModel = _dashboardProvider.GetTreeModelByCompany(companyId, userModel);
return new xPTJsonResult(null, xPTStatusCodesEnum.Success, "Loaded assets successfully");
});
}
}
even though when I check the Request in the Browser, in shows that the companyId is in the Payload.
NOTE: The same function works when I post a ViewModel
EDIT
In the above scenario I am only passing one Parameter to the controller, but in some cases I want to be able to pass 2 or 3 parameters without using a ViewModel.
e.g.
public IActionResult GetAssetListByCompany([FromBody]int companyId, [FromBody]int assetId)
{....
OR
public IActionResult GetAssetListByCompany([FromBody]int companyId, [FromBody]int assetId, [FromBody]bool canEdit = false)
{.....
and then on the client side I can do this:
this.apiService.post('/api/Dashboard/GetAssetListByCompany', { companyId: selectedCompany.id, assetId: 123 }.....
OR
this.apiService.post('/api/Dashboard/GetAssetListByCompany', { companyId: selectedCompany.id, canEdit: true, assetId: 22 }....