如何在 ASP.NET Core MVC 的同一视图中添加/创建多个一对多关系

Posted

技术标签:

【中文标题】如何在 ASP.NET Core MVC 的同一视图中添加/创建多个一对多关系【英文标题】:How to add/create multiple one-to many relationships in same view in ASP.NET Core MVC 【发布时间】:2022-01-19 21:52:32 【问题描述】:

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

我有一堂课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; 

还有另一个班级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();
    

感谢您的帮助!

【问题讨论】:

【参考方案1】:

我编写了一个演示来展示如何在同一视图中添加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");
        

【讨论】:

谢谢!我试试看! 如果我的回答能帮助您解决问题,您能接受吗?参考:meta.stackexchange.com/questions/5234/…。谢谢。

以上是关于如何在 ASP.NET Core MVC 的同一视图中添加/创建多个一对多关系的主要内容,如果未能解决你的问题,请参考以下文章

使用 ASP.NET Core MVC,如何显示图像?

如何使用 C# 在 ASP.NET Core 3.1 MVC 中使用会话变量

ASP.NET Core 5 MVC/RazorPages 和 WebAPI 项目在同一个解决方案中

ASP.NET Core MVC RedirectToAction 不工作

如何在 ASP.NET Core 5 MVC (.NET 5) 中获取记录的用户数据?

asp.net mvc 如何添加css