【问题标题】:ASP.NET Razor - How to create a POST form for List of objects?ASP.NET Razor - 如何为对象列表创建 POST 表单?
【发布时间】:2021-12-13 11:11:00
【问题描述】:

我需要创建一个 POST 表单来将新对象添加到数据库。我必须创建一个 Razor 页面,我可以在其中单击按钮添加新的课程表。在单击另一个按钮之后,所有课程都应添加到数据库上下文中。我仍然不知道该怎么做,所以我希望你能帮助我

 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; }
}

这是我的意思的一些图像:

DB 有一个 Course 表和一个 Lesson 表。请告诉我如何创建一个页面来创建具有动态“课程”数量的新“课程”

【问题讨论】:

  • lessons可以是多个吗?
  • 可以,可以是多个
  • 为此,您需要使用`List 参数创建一个方法并使用cshtml 发布数据。也可以直接将课程模型传入参数。
  • Adding a related entity可以参考官方文档。

标签: asp.net asp.net-mvc asp.net-core razor razor-pages


【解决方案1】:

请在您需要从页面传递的控制器方法中尝试使用此方法。

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
        }
    }
}

请注意,在此示例中,您将在 databases 中执行许多操作 为此,您还必须管理 transaction

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-29
    • 2020-06-17
    • 2019-04-05
    • 2011-03-12
    • 2014-07-22
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    相关资源
    最近更新 更多