user18347947
user18347947

Reputation: 3

Insert data in a table from another model In .NET Core MVC

I'm trying to build a quiz application and i want to insert the user's answers after the quiz is submitted. this is my question model:

public class Question
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Id Question")]
    public int id_question { get; set; }

    [Column(TypeName = "varchar(100)")]
    [Display(Name = "Question")]
    public string question { get; set; }

    public string option1 { get; set; }
    public string option2 { get; set; }
    public string option3 { get; set; }
    public string option4 { get; set; }

    public string answer { get; set; }

    public virtual List<Result> Results { get; set; }
}

And this is the Result model where i want to store the user's answers:

public class Result
{
    [Key]
    [Display(Name ="Id Result")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public int id_result { get; set; }

    [ForeignKey("User")]
    [Required]
    public string Id_User { get; set; }

    [Display(Name = "user")]
    [NotMapped]
    public string User_Name { get; set; }

    [ForeignKey("Question")]
    [Required]
    public int id_question { get; set; }

    [Display(Name = "Question")]
    [NotMapped]
    public string q { get; set; }
    public string UserAnswer { get; set; }
    public virtual ApplicationUser User { get; set; }
    public virtual Question Question { get; set; }
}

After storing an exam's questions in the database I want to display them like this and store the answers after submitting them:

@model IEnumerable<Exam.Areas.Identity.Data.Question>
@{
    ViewData["Title"] = "Exam";
}

<div>
    <h4>Question</h4>
    <hr />

    @foreach (var item in Model)
    {
        <div class="row pl-5">
            <div class="col-md-4">
                <div>@Html.DisplayFor(modelItem => item.question)</div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option1" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option1)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option2" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option2)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option3" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option3)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="@item.option4" name="@item.id_question" id="">
                    <label class="form-check-label" for="">
                        @Html.DisplayFor(modelItem => item.option4)
                    </label>
                </div>
            </div>
        </div>

    }

I've tried many things in vain. Can anyone help me figure out a way to approach this?

Upvotes: 0

Views: 1495

Answers (1)

Jason Pan
Jason Pan

Reputation: 22067

Judging by Rahul Sharma's comment you responded to, your question might be how to store the answer in the Results table. If we want to answer multiple questions and submit them in one page, we can pass the questions and corresponding answers back to the controller as a List collection and store them in the database to call. If you allow calling multiple models to load data, you can refer to the following sample code.

Models:

Questions.cs:

public class Question
{
        [Key]
        public int id_question { get; set; }

        [Column(TypeName = "varchar(100)")]
        [Display(Name = "Question")]
        public string question { get; set; }

        public string option1 { get; set; }
        public string option2 { get; set; }
        public string option3 { get; set; }
        public string option4 { get; set; }

        public string answer { get; set; }

}

Result.cs:

public class Result
{
        [Key]
        [Display(Name = "Id Result")]
        public int id_result { get; set; }
        [Required]
        public int Id_User { get; set; }
        [Required]
        public string User_Name { get; set; }

        [ForeignKey("Question")]
        [Required]
        public int id_question { get; set; }

        public string q { get; set; }
        public string UserAnswer { get; set; }
}

ApplicationUser.cs:

public class ApplicationUser
{
        [Key]
        [Required]
        public int Id { get; set; }
        [Required]
        public int Id_User { get; set; }
        [Required]
        public string User_Name { get; set; }   
}

Controller: QuestionAndResultController.cs:

public class QuestionAndResultController : Controller
{

        private readonly MyDbContext _myDbContext;

        public QuestionAndResultController(MyDbContext myDbContext)
        {
            _myDbContext = myDbContext;

        }

       
        public async Task<IActionResult> Index()
        {
            var question = from m in _myDbContext.Question
                           select m;
            ViewBag.UserRecord = await (from m in _myDbContext.ApplicationUser select m).ToListAsync();
            ViewBag.ResultRecord = await (from m in _myDbContext.Result select m).ToListAsync();
            
            return View(await question.ToListAsync());
        }

        [HttpGet]
        public async Task<IActionResult> ResultAnswer()
        {
            var  question = await (from m in _myDbContext.Question select m).ToListAsync();
            ViewBag.Question = question;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ResultAnswer(int Id_User,List<int> id_question, List<string> UserAnswer, List<string> q,string User_Name)
        {
            if (ModelState.IsValid)
            {
                var UserRecord = await (from m in _myDbContext.ApplicationUser select m).ToListAsync();
                bool Exist = false;
                foreach (var item in UserRecord)
                {
                    if (item.Id_User == Id_User && item.User_Name == User_Name)
                        Exist = true;
                }
                if (!Exist)
                {
                    ApplicationUser user = new ApplicationUser();
                    user.Id_User = Id_User;
                    user.User_Name = User_Name;
                    _myDbContext.ApplicationUser.Add(user);
                    await _myDbContext.SaveChangesAsync();
                    for (int i = 0; i < UserAnswer.Count; i++)
                    {
                        Result result = new Result();
                        result.Id_User = Id_User;
                        result.id_question = id_question[i];
                        result.UserAnswer = UserAnswer[i];
                        result.User_Name = User_Name;
                        result.q = q[i];
                        _myDbContext.Result.Add(result);
                        await _myDbContext.SaveChangesAsync();
                    }
                }
                else
                { 
                    var ResultRecord = await (from m in _myDbContext.Result select m).ToListAsync();
                    foreach (var item in ResultRecord)
                    {
                        if (item.Id_User == Id_User && item.User_Name == User_Name)
                        {
                            for (int i = 0; i < UserAnswer.Count; i++) {
                                if (item.id_question == id_question[i])
                                {
                                    item.UserAnswer = UserAnswer[i];
                                    _myDbContext.Result.Update(item);
                                    await _myDbContext.SaveChangesAsync();
                                }
                            }
                        }
                    }
                }
                
                return RedirectToAction(nameof(Index));
            }
            return View();
        }
}

View: Index.cshtml:

@model IEnumerable<TableTest.Models.Question>

@{
    ViewData["Title"] = "Index";
}

<h1>Question</h1>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.question)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option1)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option2)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option3)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.option4)
            </th>
            <th>
               @Html.DisplayNameFor(model => model.answer)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model) {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.question)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option1)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option2)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option3)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.option4)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.answer)
                </td>
            </tr>
        }
    </tbody>
</table>
<a class="btn btn-primary" asp-action="ResultAnswer">answer</a>

<h1>Result</h1>
<table class="table">
    <thead>
        <tr>
            <th>id_user</th>
            <th>user_name</th>
            @for (var i = 0; i < @Model.Count(); i++)
            {
                <th>qurstion@(i+1)</th>
                <th>UserAnswer</th>
            }
        </tr>
    </thead>
    <tbody>
            @foreach (var itemUser in @ViewBag.UserRecord)
            {
                <tr>
                    <td>@itemUser.Id_User</td>
                    <td>@itemUser.User_Name</td>
                    @foreach (var itemResult in @ViewBag.ResultRecord)
                    {
                        @if (@itemResult.Id_User == @itemUser.Id_User && @itemResult.User_Name == @itemUser.User_Name)
                        {
                            <td>@itemResult.q</td>
                            <td>@itemResult.UserAnswer</td>
                        }
                    }
                </tr>
            }
   </tbody>
    
</table>

ResultAnswer.cshtml:
@model TableTest.Models.Result

@{
    ViewData["Title"] = "Login";
}

<div class="row">
    <div class="col-md-4">
        <form asp-action="ResultAnswer">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Id_User" class="control-label"></label>
                <input asp-for="Id_User" class="form-control" />
                <span asp-validation-for="Id_User" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="User_Name" class="control-label"></label>
                <input asp-for="User_Name" class="form-control" />
                <span asp-validation-for="User_Name" class="text-danger"></span>
            </div>
            
            <div>Below is the question</div>
            @foreach (var item in @ViewBag.Question)
            {
                <div>@item.question</div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option1" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option1
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option2" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option2
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option3" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option3
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <div>
                    <label class="PillList-item">
                        <input id="Check" type="CheckBox" name="@item.option4" value="@item.id_question"/>
                        <span class="PillList-label" >
                            @item.option4
                            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
                        </span>
                    </label>
                </div>
                <input type="hidden" asp-for="UserAnswer" id="@item.id_question" />
                <input type="hidden" asp-for="id_question" value = "@item.id_question"/>
                <input type="hidden" asp-for="q" value = "@item.question"/>
            }
            <div class="form-group">
                <input type="submit" value="Submit" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script>
    $('input[type=checkbox]').change(function(){
          if($(this).is(":checked")){
              var value = this.attributes.name.value;
              var id = this.attributes.value.value;
              $("#"+id).attr("value",value);  
          }
          
    })
</script>

Test Result:

Index page:

enter image description here

Click on "answer":

enter image description here

Click on "Submit":

enter image description here

Upvotes: 1

Related Questions