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

Time:12-25

I'm struggling with the following:

I have a 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; }
}

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

I want a user to be able to add a question with one or more answers from the same view. I am a newbie and not able to figure this out. At this moment I only have the possibility to create a question linked to a category in the Create view.

This is the QuestionController:

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

Thanks for your help!

CodePudding user response:

I wirte a demo to show how to add one to many relationship tables in the same view:

model

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

view

@model upload111.Models.QA

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

    <div >
        <div id="inputFormRow" style="width: 35%">
            <div >
                <br />
                <div ></div>
            </div>
        </div>
        <div id="newRow">
            <input type="hidden" id="totalLans" value="0" />
        </div>
        <button id="addRow" type="button" >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 >'; 

                //change id attribute to name attribute and modify the name
        html  = '<input type="text" name="answer['   (rowCount - 1)   '].AnswerText"  placeholder="AnswerText" autocomplete="off" style="width: 30%" required>';
        html  = '<input type="text" name="answer['   (rowCount - 1)   '].Class"  placeholder="Class" autocomplete="off" style="width: 30%" required>';
        html  = '<div >';
        html  = '<button id="removeRow" type="button"  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>
}

controller

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

enter image description here

  • Related