【发布时间】:2016-12-31 15:27:53
【问题描述】:
我正在使用带有 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 }....
【问题讨论】:
-
不要使用名称 MVC6,它被称为“ASP.NET Core MVC”,版本号是 1.0.0,而不是 6。
-
有理由不使用视图模型吗?
-
@ademcaglin 因为这个方法只有一个参数 - 我不想为所有采用一两个参数的方法创建 ViewModel - 在旧的 MVC/API 中可以发布{variableName: Value}
标签: angularjs asp.net-core asp.net-core-mvc asp.net-core-webapi