POST不添加员工详细信息

时间:2020-06-28 12:50:09

标签: json reactjs rxjs react-bootstrap webapi

我是新来的反应者,正在使用Web api post,get,put删除方法向引导表添加或删除值。我正在使用post方法将值添加到引导表,这使我在添加值时成功添加,如果添加失败,则说添加失败。我意识到我的日期选择器会获取日期和时间的值,而Web api中的值只是日期,因此我添加了一个字符串doj以仅添加日期。但是它仍然显示添加失败。

以下是在Visual Studio代码中进行反应的代码:

class AddEmpModal extends Component{
    constructor(props){
        super(props);
    
        this.state = {deps:[],sanackbaropen: false, snackbarmsg:''};
    
        this.handleSubmit = this.handleSubmit.bind(this);
        }

         componentDidMount()
         {
             fetch('https://localhost:44363/api/department')
             .then(response=> response.json())
             .then(data=>{
              this.setState({deps:data});

             });
         }

        snackbarClose = (event) =>{
            this.setState({snackbaropen:false});
          };

        

        handleSubmit(event){
            event.preventDefault();
    
            fetch('https://localhost:44363/api/Employee',{
            
            method:'POST',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
    
            },
            body:JSON.stringify({
              EmployeeID:null,
              EmployeeName: event.target.EmployeeName.value,
              Department: event.target.Department.value,
              MailID: event.target.MailID.value,
              DOJ: event.target.DOJ.value,
            })
          })
            .then(res=> res.json())
            .then((result)=>
            {
              //alert(result);
              this.setState({snackbaropen:true,snackbarmsg:result})
            },
            (error)=>{
             // alert('Failed')
             this.setState({snackbaropen:true,snackbarmsg:'failed'})
          
            })
        }
        render(){
            return(
              <div className="container">
                <Snackbar
                anchorOrigin={{vertical:"top",horizontal:'center'}}
                open ={this.state.snackbaropen}
                autoHideDuration = {3000}
                onClose={this.snackbarClose}
                message = {<span id= "message-id">{this.state.snackbarmsg}</span>}
                action={[
                  <IconButton
                  key="close"
                  aria-label="Close"
                  color="inherit"
                  onClick={this.snackbarClose}
                  >
                    X
                  </IconButton>
                ]}    />
        
               
                <Modal
              {...this.props}
              size="lg"
              aria-labelledby="contained-modal-title-vcenter"
              centered
            >
              
              <Modal.Header closeButton>
                <Modal.Title id="contained-modal-title-vcenter">
                  Add Employee
                </Modal.Title>
              </Modal.Header>
              <Modal.Body>
                
                    <Row>
                        <Col sm={6}>
                            <Form onSubmit={this.handleSubmit}>
                              <Form.Group controlId="EmployeeName">
                                  <Form.Label>Employee Name</Form.Label>
                                  <Form.Control
                                      type = "text"
                                      name="EmployeeName"
                                      required
                                      placeholder="Employee Name"
                                      />
                              </Form.Group>
                              <Form.Group controlId="Department">
                                  <Form.Label>Department</Form.Label>
                                  <Form.Control as="select">
                                     {this.state.deps.map(dep =>
                                        <option key={dep.DepartmentID}>{dep.DepartmentName}</option>
                                        )}
                                  </Form.Control>
                              </Form.Group>
                              <Form.Group controlId="MailID">
                                  <Form.Label>Employee Name</Form.Label>
                                  <Form.Control
                                      type = "text"
                                      name="MailID"
                                      required
                                      placeholder="MailID"
                                      />
                              </Form.Group>
                              <Form.Group controlId="DOJ">
                                  <Form.Label>DOJ</Form.Label>
                                  <Form.Control
                                      type = "date"
                                      name="DOJ"
                                      required
                                      placeholder="DOJ"
                                      />
                              </Form.Group>
                              
                              <Form.Group>
                                  <Button variant="primary" type ="submit">
                                      Add Employee
                                  </Button>
                              </Form.Group>
                            </Form>
                        </Col>
                        </Row>
               
              </Modal.Body>
              <Modal.Footer>
                <Button variant= "danger" onClick={this.props.onHide}>Close</Button>
              </Modal.Footer>
            </Modal>
            </div>
            );
 }}
        
        export default AddEmpModal;

这是Web api员工控制器Visual Studio的代码:

namespace WebAPI.Controllers
{
    public class EmployeeController : ApiController
    {
        public HttpResponseMessage Get()
        {
            DataTable table = new DataTable();
            string query = @"
            select EmployeeID,EmployeeName,Department, 
                       MailID,
                       convert(varchar(10),DOJ,120) as DOJ
                       from dbo.Employees";

            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 Request.CreateResponse(HttpStatusCode.OK, table);

        }

        public string Post(Employee emp)
        {
            try
            {
                DataTable table = new DataTable();

                string doj = emp.DOJ.ToString().Split(' ')[0];

                string query = @"
                insert into dbo.Employees
                (EmployeeName,
                Department,
                MailID,
                DOJ)
                Values
                (
                 '" + emp.EmployeeName + @"',
                 '" + emp.Department + @"',
                 '" + emp.MailID + @"',
                 '" + emp.DOJ + @"'
                 )
                    ";

                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 "Added Successfully";
            }
            catch (Exception )
            {
                return "Failed to Add";
            }
        }

        public string Put(Employee emp)
        {
            try
            {
                DataTable table = new DataTable();

           string query = @"
            update dbo.Employees set 
            EmployeeName = '" + emp.EmployeeName + @"'
            ,Department = '" + emp.Department + @"'
            ,MailID= '" + emp.MailID + @"'
            ,DOJ = '" + emp.DOJ + @"'
            where EmployeeID = " + emp.EmployeeID + @"
                             ";

                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 "Updated Successfully";
            }
            catch (Exception)
            {
                return "Failed to Update";
            }
        }

        public string Delete(int id)
        {
            try
            {
                DataTable table = new DataTable();

                string query = @"
                 delete from dbo.Employees where EmployeeID =  " + 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";
            }
        }
    }
}

我在Web api员工控制器的POST方法中添加了此代码,以仅获取日期

string doj = emp.DOJ.ToString().Split(' ')[0];

但是它仍然显示添加失败。有人可以帮我吗?

0 个答案:

没有答案