我正在使用带有 TypeScript 和 ASP.NET Core MVC/API 的 Angular JS。
我有一个apiService
处理所有POST
和GET
对服务器的请求,它看起来像这样:
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);
}
}
}
}
现在,当我发送此请求时:
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);
});
}
它没有绑定companyId
控制器中的
这是控制器:
[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");
});
}
}
即使当我在浏览器中检查请求时,显示 companyId 在有效负载中。
注意:当我发布 ViewModel 时,同样的功能有效
编辑
在上述场景中,我只将一个参数传递给控制器,但在某些情况下,我希望能够在不使用 ViewModel 的情况下传递 2 个或 3 个参数。
例如
public IActionResult GetAssetListByCompany([FromBody]int companyId, [FromBody]int assetId)
{....
或者
public IActionResult GetAssetListByCompany([FromBody]int companyId, [FromBody]int assetId, [FromBody]bool canEdit = false)
{.....
然后在客户端我可以这样做:
this.apiService.post('/api/Dashboard/GetAssetListByCompany', { companyId: selectedCompany.id, assetId: 123 }.....
或者
this.apiService.post('/api/Dashboard/GetAssetListByCompany', { companyId: selectedCompany.id, canEdit: true, assetId: 22 }....