I am new to.NET Visual Studio and building an ASP.NET MVC Application.
This is my code and I am getting error on the Add Part
namespace proj.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
emp_RegEntities dbObj = new emp_RegEntities();
public ActionResult Employee()
{
return View();
}
[HttpPost]
public ActionResult AddEmployee(Detail model)
{
Detail obj = new Detail();
obj.EmpName = model.EmpName;
obj.Contact = model.Contact;
obj.City = model.City;
obj.State = model.State;
obj.Field = model.Field;
dbObj.Detail.Add(obj);
dbObj.SaveChanges();
return View("Employee");
}
}
}
CodePudding user response:
A sugguestion and hope this gets solve your problem.
Initialize the object inside the constructor
Dipose the object when class dispose
More Refined Code
namespace proj.Controllers
{
public class EmployeeController : Controller
{
private emp_RegEntities dbObj;
// Initialize dbObj inside Constructor
public EmployeeController()
{
dbObj = new emp_RegEntities();
}
//Dispose of dbObj when EmployeeController class dispose
protected override void Dispose(bool disposing)
{
dbObj.Dispose();
}
public ActionResult Employee()
{
return View();
}
[HttpPost]
public ActionResult AddEmployee(Detail model)
{
Detail obj = new Detail();
obj.EmpName = model.EmpName;
obj.Contact = model.Contact;
obj.City = model.City;
obj.State = model.State;
obj.Field = model.Field;
dbObj.Detail.Add(obj);
dbObj.SaveChanges();
return View("Employee");
}
}
}
CodePudding user response:
I guess here
[HttpPost]
public ActionResult AddEmployee(Detail model)
{
Detail obj = new Detail();
obj.EmpName = model.EmpName;
obj.Contact = model.Contact;
obj.City = model.City;
obj.State = model.State;
obj.Field = model.Field;
dbObj.Detail.Add(obj);
dbObj.SaveChanges();
return View(obj); //I guess u wanna return the model
}