我正在使用ASP.NET核心Web API,并且我不知道如何在将数据插入数据库时返回某些信息,然后在响应类型上显示相关的错误或成功。我创建了一个接口,在其中定义方法,然后在服务中实现接口方法,并将数据插入数据库,然后创建连接到angular的控制器。
接口方法
void AddMurderComplian(Complians complians);
服务方法
public void AddMurderComplian(Complians complians)
{
var complianMurder = new Complians()
{
Dead = complians.Dead,
Wounded = complians.Wounded,
CriminalsInvolved = complians.CriminalsInvolved,
CriminalAppearence = complians.CriminalAppearence,
VehiclesUsed = complians.VehiclesUsed,
WeaponsDescription = complians.WeaponsDescription,
SubType = complians.SubType,
ApplicationUserId = complians.ApplicationUserId
};
try
{
_appDbContext.Complians.Add(complianMurder);
_appDbContext.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
控制器
[HttpPost]
[Route("complianMurder")]
public void Post(Complians complian)
{
_complians.AddMurderComplian(complian);
}
角度
submitMurderInfo()
{
this.formModelMurder.SubType = "Murder";
this.formModelMurder.ApplicationUserId = sessionStorage.getItem("Id");
this.murderService.murderQuestionnaire(this.formModelMurder).subscribe(
(res: any)=>{
if (res.succeeded)
{
// this.toastr.success("Welome ");
// this.formModelMurder.Dead = '',
// this.formModelMurder.Wounded ='',
// this.formModelMurder.CriminalsInvolved = '',
// this.formModelMurder.CriminalAppearence = '',
// this.formModelMurder.VehiclesUsed = '',
// this.formModelMurder.WeaponsDescription ='',
// this.formModelMurder.SubType = '',
// this.formModelMurder.ApplicationUserId = ''
}
else
{
// this.toastr.error('Sorry Check your complian');
}
});
}
答案 0 :(得分:1)
我会这样:
public bool AddMurderComplian(Complians complians)
{
bool succeeded = false;
var complianMurder = new Complians()
{
Dead = complians.Dead,
Wounded = complians.Wounded,
CriminalsInvolved = complians.CriminalsInvolved,
CriminalAppearence = complians.CriminalAppearence,
VehiclesUsed = complians.VehiclesUsed,
WeaponsDescription = complians.WeaponsDescription,
SubType = complians.SubType,
ApplicationUserId = complians.ApplicationUserId
};
try
{
_appDbContext.Complians.Add(complianMurder);
_appDbContext.SaveChanges();
succeeded = true;
return succeeded;
}
catch (Exception ex)
{
succeeded = false;
return succeeded;
}
}
在控制器方法中:
[HttpPost]
[Route("complianMurder")]
public bool Post(Complians complian)
{
return _complians.AddMurderComplian(complian);
}
成角度:
submitMurderInfo()
{
this.formModelMurder.SubType = "Murder";
this.formModelMurder.ApplicationUserId = sessionStorage.getItem("Id");
this.murderService
.murderQuestionnaire(this.formModelMurder)
.subscribe((res: any) => {
if (res) {
// Successfully inserted
} else {
// this.toastr.error('Sorry Check your complian');
}
});
}