【发布时间】:2020-06-28 06:56:58
【问题描述】:
我是新来的反应,并试图实现删除方法来删除表中的行。我正在使用 web api 删除我的 sql 表中的行。但是,我无法做到这一点。
这是 Visual Studio 代码中用于反应的代码:
class Department extends Component{
constructor(props){
super(props);
this.refreshList = this.refreshList.bind(this);
this.state={deps:[],addModalShow:false,editModalShow:false}
}
componentDidMount(){
this.refreshList();
}
refreshList(){
const that =this;
fetch('https://localhost:44363/api/department')
.then(response=>response.json())
.then(data=>{
this.setState({deps:data});
}
);
}
componentDidUpdate(){
this.refreshList();
}
deleteDep(depid)
{
if(window.confirm('Are you sure?'))
{
fetch('https://localhost:44363/api/department'+depid,{
method:'DELETE',
header:{'Accept':'application/json',
'Content-Type':'application/json'
}
})
}
}
render(){
const {deps,depid,depname} = this.state;
let addModalClose = () => this.setState({addModalShow:false});
let editModalClose = () => this.setState({editModalShow:false});
return(
<div>
<Table className="mt-4" striped bordered hover size="sm">
<thead>
<tr>
<th>DepartmentId</th>
<th>DepartmentName</th>
<th>Option</th>
</tr>
</thead>
<tbody>
{deps.map(dep =>
<tr key = {dep.DepartmentID}>
<td>{dep.DepartmentID}</td>
<td>{dep.DepartmentName}</td>
<td>
<ButtonToolbar>
<Button
className="mr-2"
variant="info"
onClick={()=>
this.setState({editModalShow:true,depid:dep.DepartmentID,depname:dep.DepartmentName})
}>
Edit
</Button >
<Button className="mr-2"
onClick= {()=>this.deleteDep(dep.DepartmentID)}
variant ="danger" >
Delete
</Button>
<EditDepModal
show={this.state.editModalShow}
onHide={editModalClose}
depid = {depid}
depname={depname}
/>
</ButtonToolbar>
</td>
</tr>
)}
</tbody>
</Table>
<ButtonToolbar>
<Button
variant='primary'
onClick={()=>this.setState({addModalShow:true})}>
Add Department
</Button>
<AddDepModal
show={this.state.addModalShow}
onHide={addModalClose}/>
</ButtonToolbar>
</div>
)
}
}
export default Department;
这是我在 Visual Studio 中实现的 Delete 方法:
public string Delete(int id)
{
try
{
DataTable table = new DataTable();
string query = @"
delete from dbo.Departments where DepartmentID = " + id;
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeAppDB"].ConnectionString))
using (var cmd = new SqlCommand(query, con))
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.Text;
da.Fill(table);
}
return "Deleted Successfully";
}
catch (Exception)
{
return "Failed to Delete";
}
}
}
}
我在我的 sql 表中使用 EmployeeAppDB 表
我不知道为什么我不能删除。窗口弹出来但是删除功能没有发生。请帮忙
【问题讨论】:
标签: javascript reactjs react-redux react-bootstrap webapi