Reputation: 173
I need save employee details to database. My idea is to send employee data from Controller to reacjts as json format and reactjs should call webapi post method . Webapi take care of saving data in sql server.
My web api code:
//Insert new Employee
public IHttpActionResult CreateNewEmployee(EmployeeModels emp)
{
using (var ctx = new Employee())
{
ctx.tempemp.Add(new tempemp()
{
Id = emp.Id,
name = emp.name,
mobile = emp.mobile,
erole = emp.erole,
dept = emp.dept,
email = emp.email
});
ctx.SaveChanges();
}
return Ok();
}
my Controller :
[HttpPost]
public JsonResult CreateNew(Employee model)
{
return Json(model);
}
Kindly provide some suggestion to send my employee model to reactjs. Im new to reactjs. im trying to pass the data from controller to reactjs.
Upvotes: 1
Views: 8484
Reputation: 1609
This api action does the SQL insert for you.
//Insert new Employee
public IHttpActionResult CreateNewEmployee(EmployeeModels emp)
{
using (var ctx = new Employee())
{
ctx.tempemp.Add(new tempemp()
{
Id = emp.Id,
name = emp.name,
mobile = emp.mobile,
erole = emp.erole,
dept = emp.dept,
email = emp.email
});
ctx.SaveChanges();
}
return Ok();
}
If you are trying to register an employee through this method, you are posting the employee details to the method (From react as you've mentioned).
This function returns a function, the ok()
function.
I have no idea what ok()
is. Hope it is a message that the employee is created.
If you want to display the employee details in react, you should `get the employee from the database.
[HttpGet]
public JsonResult GetEmployeeDetails(int EmployeeId)
{
//here, DatabaseContext.Employees is your DBContext and Employees table.
var model = DatabaseContext.Employees.SingleOrDefault(x=>x.Id == EmployeeId);
return Json(model);
}
refer this question for reference on how to call the API. calling api is same, irrespective of back end languages.
Also, here is a sample asp.net-react app for reference.
hope this answers your question. please comment your queries.
Upvotes: 1
Reputation: 1515
Here is the code
First you need to create model as javascript object same as your class in .net
eg.
class Employee{ //.net class
public int EmployeeId {get; set;}
public string EmployeeName {get; set;}
}
let employee={ //js
EmployeeId:10,
EmployeeName:"abc"
}
now you can pass this object as param to your controller and call api with updated model
//Call Controller
fetch('https://mywebsite.com/CreateNew/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(employee)
})
.then(function(resp){
// Call API
fetch('https://api.com/CreateNewEmployee/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(resp)
})
.then(function(resp){
// check resp.status == 200
})
})
MVC will auto-bind model by comparing property name.
Upvotes: 1