Skip to content

Instantly share code, notes, and snippets.

@rahuldass
Created September 6, 2015 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rahuldass/47d65d9001e7a8c3fabd to your computer and use it in GitHub Desktop.
Save rahuldass/47d65d9001e7a8c3fabd to your computer and use it in GitHub Desktop.
Insert data in MVC 4 #mvc4

###Insert data in MVC 4

Insert record in database using Entity Framework

Method 1 using FormCollection

[HttpPost]
public ActionResult Create(FormCollection formCollection)
{
    if (ModelState.IsValid)
    {
        Employee employee = new Employee();
        
        employee.Name = formCollection["Name"];
        employee.Gender = formCollection["Gender"];
        employee.City = formCollection["City"];
        employee.DateOfBirth = Convert.ToDateTime(formCollection["DateOfBirth"]);
        
        EmployeeContext employeeContext = new EmployeeContext();
        employeeContext.Employees.Add(employee);
        employeeContext.SaveChanges();

        return RedirectToAction("Index");
    }
    return View();
}

Method 2 using object as a parameter

[HttpPost]
public ActionResult Create(Employee employee)
{
    if (ModelState.IsValid)
    {
        EmployeeContext employeeContext = new EmployeeContext();
        employeeContext.Employees.Add(employee);
        employeeContext.SaveChanges();

        return RedirectToAction("Index");
    }
    return View();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment