Saturday, January 15, 2011

Asp .Net Mvc with Entity Framework










































































public ActionResult Index()
{
var Grp = context.ContactGroups;
return View(Grp);
}







//
// GET: /Home/Create

public ActionResult Create()
{
return View();
}

//
// POST: /Home/Create

[HttpPost]
public ActionResult Create(ContactGroup Grp)
{
if (ModelState.IsValid)
{
try
{
context.AddToContactGroups(Grp);
context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View(Grp);
}
}
else
{
return View(Grp);
}
}





//
// GET: /Home/Edit/5

public ActionResult Edit(int id)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);
return View(Grp);
}

//
// POST: /Home/Edit/5

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);

try
{
UpdateModel(Grp, collection.ToValueProvider());
context.SaveChanges();

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






//
// GET: /Home/Delete/5

public ActionResult Delete(int id)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);
return View(Grp);
}

//
// POST: /Home/Delete/5

[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);

try
{
context.DeleteObject(Grp);
context.SaveChanges();

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