I have a model classroom that have an array of enrollments that have an array of components and components have an array of subcomponents. (I know it can be confusing and maybe not the best way)
public class Classroom
{
...
public virtual List<Enrollment> Enrollments { get; set; }
}
public class Enrollment
{
...
public virtual int ClassroomId { get; set; }
public virtual Classroom Classroom { get; set; }
public virtual List<Components> Components { get; set; }
}
public class Component
{
...
public virtual int EnrollmentId { get; set; }
public virtual Enrollment Enrollment{ get; set; }
public virtual List<Subcomponent> Subcomponents { get; set; }
}
public class Subcomponent
{
...
public virtual int ComponentId { get; set; }
public virtual Component Component{ get; set; }
}
In a view on the enrollment i have a table to show the components and in the future the subcomponents. After creating a subcomponent i need to redirect to that enrollment view with the respective enrollment id. I have this code:
public ActionResult CreateSubcomponent(Subcomponent subcomponent)
{
if (ModelState.IsValid)
{
db.Subcomponents.Add(subcomponent);
db.SaveChanges();
return RedirectToAction("View", "Enrollment", new { id = ??? });
}
...
}
My question is how can i do it? How can i get the id from the enrollment? Do i need to change the code, and if so, how? Thanks
To save a SubComponent, you need to save the ComponentId because it is a foreign key. That means you should have the ComponentId in your action method. You should query the database to get the Component record for that ComponentId and use the Enrollement property of that entity.
public ActionResult CreateSubcomponent(Subcomponent subcomponent)
{
if (ModelState.IsValid)
{
db.Subcomponents.Add(subcomponent);
db.SaveChanges();
var c=db.Components.FirstOrDefault(s=>s.Id=subComponent.ComponentId);
var enrollmentId = c.EnrollementId;
return RedirectToAction("View", "Enrollment", new { id = enrollmentId });
}
// to do : return something
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments