skip to Main Content

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");
        }

    }
}

2

Answers


  1. A sugguestion and hope this gets solve your problem.

    1. Initialize the object inside the constructor

    2. 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");
            }
    
        }
    }
    
    Login or Signup to reply.
  2. I think the problem is you don’t pass the model object to view in the post

    [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            
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search