2

I need to create a POST form to add new objects to database. I have to create a Razor page where I can add new lesson form on click of a button. And after it on click of another button all the lessons should be added to DB context. I still don't know how to do it so I want you to help me

 public class Course
{
    public Guid Id { get; set; }
    public string Category { get; set; }
    public string Title{ get; set; }
    public List<Lesson> Lessons { get; set; } = new List<Lesson>();
}
public class Lesson
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
}

Here is some image of what I mean: enter image description here

DB has a Course table and a Lesson table. Please tell me how I can create a page to create new 'Course' with dynamic amount of 'Lessons'

1 Answers1

0

Please try with this in your controller method you need to pass from the page.

public ActionResult PostMethod(Course course, FormCollection formCollection)
{
    string title = course.Title; // Title value
    string category = course.Category; // Category value
    //add course into database
    if (course.Lessons != null && course.Lessons.Count > 0)
    {
        foreach (var item in course.Lessons)
        {
            //add Lessons into database
        }
    }
}

Please note in this example you are going to perform many operations in databases you have to manage transaction as well for this.

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

jishan siddique
  • 1,848
  • 2
  • 12
  • 23