I am new to react and web api development. I am having an issue with datetime. As I am having a datetime component in my employee model.
Code here:
Employee.cs
namespace WebAPI.Models
{
public class Employee
{
public long EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string Department { get; set; }
public string MailID { get; set; }
public DateTime DOJ { get; set; }
}
}
I am trying to add the elements from a modal popup to my database using the employee controller. However, I think it is failing due to the popup accepting date and the web api passing date time .Hence there is a mismatch when inserting. I tried to resolve this issue by adding this code below to employee controller.
string doj = emp.DOJ.ToString().Split(' ')[0];
Here is my employee controller part:
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 + @"',
'" + 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";
}
}
Here is what I am using in visual studio code:
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'})
})
}
Could you tell me a way to solve the datetime issue or tell me where I am going wrong?