如何 add/create 在 ASP.NET 核心 MVC 中的同一视图中建立多个一对多关系

How to add/create multiple one-to many relationships in same view in ASP.NET Core MVC

我正在努力解决以下问题:

我有一个 class Questions:

public class Question
{
    public int QuestionID { get; set; }
    public string QuestionText { get; set; }
    public int CategoryID { get; set; }
    public string Explanation { get; set; }

    public virtual Category Category { get; set; }

    public virtual ICollection<Answer> Answers { get; set; }
}

和另一个 class Answer:

public class Answer
{
    public int AnswerID { get; set; }
    public string AnswerText { get; set; }
    public string Class { get; set; }

    public int QuestionID { get; set; }
    public virtual Question Question { get; set; }
}

我希望用户能够从同一视图中添加一个或多个答案的问题。我是新手,无法弄清楚这一点。目前我只能在创建视图中创建一个链接到类别的问题。

这是QuestionController:

    // GET: Questions/Create
    public IActionResult Create()
    {
        ViewData["CategoryID"] = new SelectList(_context.Category, "CategoryID", "CategoryName");
        return View();
    }

感谢您的帮助!

我写了一个演示来展示如何在同一视图中添加 one to many 关系表:

型号

    public class Question
    {
        public int QuestionID { get; set; }
        public string QuestionText { get; set; }
        public string Explanation { get; set; }

        public virtual ICollection<Answer> Answers { get; set; }
    }

    public class Answer
    {
        public int AnswerID { get; set; }
        public string AnswerText { get; set; }
        public string Class { get; set; }

        public int QuestionID { get; set; }
        public virtual Question Question { get; set; }
    }

    public class QA
    {
        public IList<Answer> answer { get; set; }
        public Question question { get; set; }
    }

查看

@model upload111.Models.QA

<form asp-controller="Home" asp-action="Create" method="post">
    <div class="form-group">
        <label asp-for="@Model.question.QuestionText"></label>
        <input asp-for="@Model.question.QuestionText" />
    </div>
    <div class="form-group">
        <label asp-for="@Model.question.Explanation"></label>
        <input asp-for="@Model.question.Explanation" />
    </div>
    
    <br />
    

    <div class="form-group">
        <div id="inputFormRow" style="width: 35%">
            <div class="input-group mb-3">
                <br />
                <div class="input-group-append"></div>
            </div>
        </div>
        <div id="newRow">
            <input type="hidden" id="totalLans" value="0" />
        </div>
        <button id="addRow" type="button" class="btn btn-info">Add Network</button>    
    </div>
       
        <button type="submit" id="createButton">Add</button>
   
</form>

@section Scripts
{
    <script>
        
       $("#addRow").click(function ()
    {
       
        var rowCount = parseInt($("#totalLans").val());
        rowCount++;
        $("#totalLans").val(rowCount);
        var html = '';
        html += '<div id="inputFormRow" style="width: 35%">';
        html += '<div class="input-group mb-3">'; 

                //change id attribute to name attribute and modify the name
        html += '<input type="text" name="answer[' + (rowCount - 1) + '].AnswerText" class="form-control m-input" placeholder="AnswerText" autocomplete="off" style="width: 30%" required>';
        html += '<input type="text" name="answer[' + (rowCount - 1) + '].Class" class="form-control m-input" placeholder="Class" autocomplete="off" style="width: 30%" required>';
        html += '<div class="input-group-append">';
        html += '<button id="removeRow" type="button" class="btn btn-danger" style="margin-right: 5px">Remove Network</button>';
        html += '</div>';
        html += '</div>';

        $('#newRow').append(html);
        
    });    

    $(document).on('click', '#removeRow', function ()
    {
        var rowCount = parseInt($("#totalLans").val());
        rowCount--;
        $("#totalLans").val(rowCount);
        $(this).closest('#inputFormRow').remove();
    });    

    $(document).ready(function () {
        $("#createButton").click(function ()
        {
            var inputData = $('form').serializeArray();  
            $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Home/Create", // Controller/View
                data: inputData,
                success : function(response) {
                    console.log(response)
                }
            });

        });
    });
    </script>
}

控制器

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

        

        [HttpPost]
        public async Task<IActionResult> Create(QA q)
        {
            Question qs = new Question();
            qs.QuestionText = q.question.QuestionText;
            qs.Explanation = q.question.Explanation;
            qs.Answers = new List<Answer>();

            foreach (var item in q.answer) {
                var A = new Answer()
                {
                    AnswerText = item.AnswerText,
                    Class = item.Class

                };
                qs.Answers.Add(A);
                
            }
            
            _context.questions.Add(qs);
            _context.SaveChanges();
            
            return RedirectToAction("Index");
        }