Reputation:
I'm really new at all of this. I'm currently reading the tutorial "Getting Started with EF using MVC" on the ASP.NET website: (Chapter 6)
In the tutorial, at the part titled "Adding Course Assignments to the Instructor Edit Page" The author wrote about how to edit the Course in the instructor page:
public ActionResult Edit(int id)
{
Instructor instructor = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses)
.Where(i => i.InstructorID == id)
.Single();
PopulateAssignedCourseData(instructor);
return View(instructor);
}
public ActionResult Edit(int id, FormCollection formCollection, string[] selectedCourses)
{
var instructorToUpdate = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses)
.Where(i => i.InstructorID == id)
.Single();
if (TryUpdateModel(instructorToUpdate, "", null, new string[] { "Courses" }))
{
try
{
if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location))
{
instructorToUpdate.OfficeAssignment = null;
}
UpdateInstructorCourses(selectedCourses, instructorToUpdate);
db.Entry(instructorToUpdate).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
PopulateAssignedCourseData(instructorToUpdate);
return View(instructorToUpdate);
}
Could some one please tell me how to use the same concept (as the author) to accomplish deleting and creating action method? Or if you can direct me to a useful tutorial/site about many to many relationship with EF in MVC, especially on how to create a controller and view for many to many related data, similar to the tutorial mentioned above. I'm a beginner at this, but I still need to get work done, so it would really help if the concepts used coincides, it would be easier for me.
Thanks so much in advance!
Upvotes: 2
Views: 3242
Reputation: 155
I know this is an old thread. But I was trying to do the EXACT same thing
Here's my solution
//
// GET: /Project/Create/
public ActionResult Create()
{
var project = new Project();
ViewBag.Themes = db.Theme.ToList();
return View(project);
}
//
// POST: /Project/Create/
[HttpPost]
public ActionResult Create(Project projet, string[] selectedTheme)
{
var errors = ModelState.Select(x => x.Value.Errors).ToList();
project.Themes = new List<Theme>();
if (TryUpdateModel(project, "", null, new string[] { "Theme" }))
{
try
{
UpdateProjectTheme(selectedTheme, project);
db.Project.Add(project);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Impossible to create project.");
}
}
return View(project);
}
And in the create view :
@{
List<Project.Models.Theme> themes = ViewBag.Themes;
@:<td>
foreach (var display in themes)
{
<label class="checkbox">
<input type="checkbox"
name="selectedTheme"
value="@display.ThemeID" />
@display.Name
</label>
if (display.Name.Length > 20)
{
@:<br />
}
else
{
if (display.ThemeID % 2 == 0)
{
@:<br />
}
}
}
@:</td>
@: </tr>
}
Hope you find it useful, you can also look on my SO post
Upvotes: 0
Reputation: 5247
Creation and Deletion are usually a bit simpler. I've outlined just the basic structure. The controller for the create entry page is :
public ViewResult CreateInstructor()
{
return View();
}
To generate the create form you can use the scaffolding (just right-click on View and select Add View... and then select the appropriate model and page type). The post-back of this page is handled by a controller with the [HttpPost] attribute, it will bind the data on the form to the object passed into the controller method and this is then passed to your DBContext Add() method, finally execute the SaveChanges() method to actually hit the database:
[HttpPost]
public ActionResult CreateInstructor(Instructor instructor)
{
db.Instructors.Add(instructor);
db.Instructors.SaveChanges();
return View(); //There will be some other logic here typically such as redirecting on a successful creation or showing specific validation issues with the object .
}
Delete is achieved using the DBContext Remove method, just note that you do not first have to hit the database to load the object and then again to delete it. You will typically be passed the object's id and you can then attach a new instance of the object to the context and delete it.
public ActionResult DeleteInstructor(int instructorId)
{
var instructor = new Instructor {Id = instructorId};
db.Instructors.Attach(instructor);
db.Instructors.Remove(instructor);
db.Instructors.SaveChanges();
return View();
}
Upvotes: 1