在 angular 2 和 MVC 中添加到 SQL 服务器数据库
Adding to SQL server database in angular 2 and MVC
我正在尝试使用 angular 和 MVC 向 Microsoft SQL 服务器中的 Employee table 插入一个值。
以下代码是addEmployee组件:
private EmpId: number;
public formData: FormGroup;
public constructor(private empService: EmployeeServices) {
this.empService.postData(this.EmpId)
.subscribe(
(data: Response) => (data.json())
);
this.formData = new FormGroup({
'EmployeeName': new FormControl('', [Validators.required]),
'EmployeeSalary': new FormControl('',[Validators.required])
});
}
onSubmit() {
if (this.formData.valid) {
var Obj = {
EmployeeName: this.formData.value.EmployeeName,
EmployeeSalary: this.formData.value.EmployeeSalary,
};
this.empService.postData(Obj).subscribe();
alert("Employee Inserted Successfully");
}
}
但是,当我尝试 运行 时,没有任何反应,而且我输入的值也没有发布到数据库中。
我的控制器是:
[HttpPost]
public IActionResult AddEmployee([FromBody]Employee empObj)
{
_context.Employee.Add(empObj);
_context.SaveChanges();
return Json("OK");
}
服务是:
postData(empObj: any) {
let headers = new Headers({
'Content-Type':
'application/json; charset=utf-8'
});
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:65291/api/employee', JSON.stringify(empObj), options);
}
在add组件中写什么可以让系统成功添加数据库?
首先,在您的控制器函数中放置一个断点以确保该函数被触发。
其次,你的 url
'http://localhost:65291/api/**employee**'
和控制器函数名称不匹配
public IActionResult **AddEmployee**()
我正在尝试使用 angular 和 MVC 向 Microsoft SQL 服务器中的 Employee table 插入一个值。
以下代码是addEmployee组件:
private EmpId: number;
public formData: FormGroup;
public constructor(private empService: EmployeeServices) {
this.empService.postData(this.EmpId)
.subscribe(
(data: Response) => (data.json())
);
this.formData = new FormGroup({
'EmployeeName': new FormControl('', [Validators.required]),
'EmployeeSalary': new FormControl('',[Validators.required])
});
}
onSubmit() {
if (this.formData.valid) {
var Obj = {
EmployeeName: this.formData.value.EmployeeName,
EmployeeSalary: this.formData.value.EmployeeSalary,
};
this.empService.postData(Obj).subscribe();
alert("Employee Inserted Successfully");
}
}
但是,当我尝试 运行 时,没有任何反应,而且我输入的值也没有发布到数据库中。
我的控制器是:
[HttpPost]
public IActionResult AddEmployee([FromBody]Employee empObj)
{
_context.Employee.Add(empObj);
_context.SaveChanges();
return Json("OK");
}
服务是:
postData(empObj: any) {
let headers = new Headers({
'Content-Type':
'application/json; charset=utf-8'
});
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:65291/api/employee', JSON.stringify(empObj), options);
}
在add组件中写什么可以让系统成功添加数据库?
首先,在您的控制器函数中放置一个断点以确保该函数被触发。
其次,你的 url
'http://localhost:65291/api/**employee**'
和控制器函数名称不匹配
public IActionResult **AddEmployee**()