locked
How I can choose list of questions that are not selected before ? RRS feed

  • Question

  • User1694748171 posted

    I got 60 questions, when student retake the exam it should have different question from first time. I used Except() but it;s not working. any idea please ?

    my controller 

          public ActionResult Index(string studentName , Student_Exam_ViewModel model1, int? TWRAid, DateTime? DOB,
                                             string Student_Phone_Number, int? No_of_Attempt, string errmsg, string procId, string reTake)
            {
                No_of_Attempt = No_of_Attempt == 0 ? 1 : No_of_Attempt;
                TimeSpan ts = new TimeSpan(1, 30, 0); //01:30:00 minutes
                ViewBag.Message = errmsg;
                if (reTake == null)
                {
                    TempData["TWRAid"] = TWRAid;
                    TempData["studentPhoneNo"] = Student_Phone_Number;
                    TempData["DOB"] = DOB;
                    TempData["No_of_Attempt"] = No_of_Attempt;
                    TempData["proctorId"] = procId;
                    TempData["studentName"] = studentName;
                }
    
                
                if (reTake == "1")
                {
                    TempData.Keep("TWRAid");
                    TempData.Keep("studentPhoneNo");
                    TempData.Keep("DOB");
                    //TempData.Keep("No_of_Attempt");
                    TempData["No_of_Attempt"] = 2;
                    TempData.Keep("proctorId");
                    TempData.Keep("studentName");
                  
                }
                //peopleList2.Except(peopleList1)  // Use LINQ to get items in one List<>, that are not in another List<>
                if (studentName == null)
                {
                    studentName = (string) TempData["studentName"];
                }
    
                var peakTwrAid = TempData.Peek("TWRAid");
    
                // get selected question id when re-take the exam.
              
    
                var examid = _db.Exam_Student_Enrollment.Where(x => x.TWRAId == peakTwrAid.ToString()).
                                    OrderByDescending(x => x.Exam_Date).Select(x => x.ExamId).FirstOrDefault();
                                    List<int> questionIdList = _db.Exam_Student.Where(x => x.ExamId == examid).Select(x => x.QuestionId).ToList();
    
                ViewBag.Time = ts.ToString();
                ViewBag.Name = studentName;
              
                var m1s = from A in _db.Exam_Assessment
                    // join q in db.Exam_Questions on A.Assessment_Section equals q.Assessment_Section
                    select A;
                var mod = new List<Student_Exam_ViewModel>();
                 
                foreach (var m1 in m1s)
                {
                    // var q1s = _db.Exam_Questions.OrderBy(t => Guid.NewGuid()).Where(q => q.Assessment_Section == m1.Assessment_Section && m1.Amount_of_Test_Question > 0) ;
                    var q1s = _db.Exam_Questions.Where(q => q.Assessment_Section == m1.Assessment_Section && m1.Amount_of_Test_Question > 0);
    
                  // var cqn = q1s.Select(x => x.QuestionName).OrderBy( t => Guid.NewGuid()).Take(m1.Amount_of_Test_Question).ToList();
               
                    foreach (var q1 in q1s.Take(m1.Amount_of_Test_Question)) // Iterate  through each column in db.Exam_Questions table
                    {
                        //var answerId = _db.Exam_Answers.OrderBy(t => Guid.NewGuid()).Where(x => x.QuestionId == q1.QuestionId)
                        //                                                                               .Select(x => x.AnswerId).ToList(); // with shuffle
    
                        var answerId = _db.Exam_Answers.Where(x => x.QuestionId == q1.QuestionId)
                            .Select(x => x.AnswerId).ToList();   // No shuffle
                        //foreach (var id in answerId)
                        //{
                        //    answerOptions = _db.Exam_Answers.
                        //     Where(x => x.QuestionId == q1.QuestionId && x.AnswerId == id).Select(x => x.Answer).OrderBy(t => Guid.NewGuid()).ToList();
    
                        //}
    
    
                        var answerOptions = _db.Exam_Answers.
                            Where(x => x.QuestionId == q1.QuestionId).Select(x => x.Answer).ToList(); // No shuffle
    
                        var model = new Student_Exam_ViewModel
                        {
                            GeneralQuestions = new List<Questions>
                            {
                                new Questions
                                {
                                    QuestionId = q1.QuestionId,
                                    QuestionName = q1.QuestionName,
                                    Assessment_Section = q1.Assessment_Section,
                                    Image_Path = q1.Question_Img,
                                    ImagePosition =  q1.Img_position,
                                    Amount_of_Question = m1.Amount_of_Test_Question,
                                    
                                    PossibleAnswers = new List<PossibleAnswer>
                                    {
                                        new PossibleAnswer { AnswerId  = answerId, Answer = answerOptions}
                                        
                                    }
                                }
                            }
                        };
                        mod.Add(model);
                    }
                }
    
                if (reTake == "1")
                {
                    foreach (var qid in mod)
                    {
                        //qid.GeneralQuestions.Contains(selectedQuestionId);
                    }
                }
                return View(mod.ToArray());
               
            }

    and my view

    @*@model IEnumerable<BoatSafetyExam.ViewModels.Student_Exam_ViewModel>*@
    
    @using System.Web.Mvc.Html
    @model BoatSafetyExam.ViewModels.Student_Exam_ViewModel[]
    @{
        ViewBag.Title = "Index";
        Layout = "~/Views/Shared/_MasterLayout2.cshtml";
    }
    
    <link href="~/Content/Student_Exam.css?v1.6" rel="stylesheet" />
    <link href="~/Content/addAsterisk.css?v.5" rel="stylesheet" />
    <div class="form-group">
        <div class="indent7" style="color:black; font-weight:bold; font-family:Arial" ;padding-top:1px>Read the Questions and answer carefully</div>
        <br />
        <div class="indent8" style="color:black; font-weight:bold; font-family:Arial" ;padding-top:1px>Submit your answer by clicking on the finished button at the bottom of this page.</div>
    </div>
    
    <br />
    <hr />
    @Html.Partial("_InputValidation")
    @Html.Partial("_preventBackButton")
    
    <style>
        input[type=radio] {
            -ms-transform: scale(1.5); /* IE 9 */
            -webkit-transform: scale(1.5); /* Chrome, Safari, Opera */
            transform: scale(1.5);
        }
    </style>
    
    <script>
        document.onkeydown = function () {
            if (event.keyCode == 116) {
                event.returnValue = false;
                event.keyCode = 0;
                return false;
            }
        }
    </script>
    
    <div id="hms" class="hms" hidden="hidden">@ViewBag.Time</div>
    <div id="countTime" hidden="hidden"></div>
    <script type="text/javascript">
        // localStorage.removeItem("counter");
    
        var startTime = document.getElementById('hms').innerHTML;
    
        if (localStorage.getItem("counter")) {
            if (getjudgetime(localStorage.getItem("counter"))) {
                var value = startTime;
            } else {
                var value = localStorage.getItem("counter");
            }
        } else {
            var value = startTime;
        }
        document.getElementById('countTime').innerHTML = value;
        var counter = function () {
            if (getjudgetime(value)) {
                localStorage.setItem("counter", startTime);
                value = startTime;
            } else {
                value = getnewtimestring(value);
                localStorage.setItem("counter", value);
            }
            document.getElementById('countTime').innerHTML = value;
        };
        var interval = setInterval(counter, 1000);
    
        function getnewtimestring(oTime) {
            var timedif = new Date(getnewtime(oTime).valueOf() - 1000);
            var newtime = timedif.toTimeString().split(" ")[0];
            return newtime;
        }
        function getnewtime(oTime) {
            var pieces = oTime.split(":");
            var time = new Date();
            time.setHours(pieces[0]);
            time.setMinutes(pieces[1]);
            time.setSeconds(pieces[2]);
            return time;
        }
        function getjudgetime(jTime) {
            return getnewtime(jTime) <= getnewtime("00:00:00") ? true : false
        }
    </script>
    
    <br />
    
    @using (Html.BeginForm("GetTestResult", "Student_Exam", FormMethod.Post, new { id = "thisForm" }))
    {
    
        @Html.AntiForgeryToken()
    
        <div id="messageDiv" style="clear: left; display: block; color: red; width: 490px;">
            @ViewBag.Message
        </div>
    
        <div class="form-group">
            @*@for (var modelIndex = 0; modelIndex < Model.Length; ++modelIndex)*@
            @for (var modelIndex = 0; modelIndex < 3; ++modelIndex)
            {
                for (var questionIndex = 0; questionIndex < Model[modelIndex].GeneralQuestions.Count; questionIndex++)
                {
                    var question = Model[modelIndex].GeneralQuestions[questionIndex];
                    var item = Model[modelIndex].GeneralQuestions[questionIndex];
                    var indexCount = modelIndex + 1;
    
            <div class="form-group">
                <div class="border border-primary col-md-12">
    
                    <div class="col-md-12 shadow-sm p-4 mb-4 bg-light font-weight-bold" style="font-family:Arial">
                        @Html.HiddenFor(m => m[modelIndex].GeneralQuestions[questionIndex].QuestionId)
                        @Html.HiddenFor(m => m[modelIndex].GeneralQuestions[questionIndex].QuestionName)
                        @Html.HiddenFor(m => m[modelIndex].GeneralQuestions[questionIndex].AssessmentId)
                        @Html.HiddenFor(m => m[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers)
    
    
                        <ul   style="list-style-type:none;">
                            <li>
                                @if (@Model[modelIndex].GeneralQuestions[questionIndex].Image_Path != null)
                                {
                                    if (@Model[modelIndex].GeneralQuestions[questionIndex].ImagePosition == 1)
                                    {
                                        <img src="~/Images/@Model[modelIndex].GeneralQuestions[questionIndex].Image_Path" style=" color:white; border-width: 0; margin: 10px 10px 10px 10px;" />
    
                                        <span>@indexCount - </span>
                                        @Html.DisplayFor(m => m[modelIndex].GeneralQuestions[questionIndex].QuestionName,
                                       new
                                       {
                                           @class = " noWrap form-control",
                                           @style = "font-weight:bold;",
                                           @size = "25px",
                                           @required = "required"
    
                                       }
                                       )
    
                                    }
    
                                    if (@Model[modelIndex].GeneralQuestions[questionIndex].ImagePosition == 2)
                                    {
                                        <div class="row">
                                            <span>@indexCount - </span>
    
                                            @Html.DisplayFor(m => m[modelIndex].GeneralQuestions[questionIndex].QuestionName,
                                              new
                                              {
                                                  @class = "required noWrap form-control",
                                                  @style = "font-weight:bold;"
                                              }
                                              )
                                            <img src="~/Images/@Model[modelIndex].GeneralQuestions[questionIndex].Image_Path" style=" color:white; border-width: 0; margin: 10px 10px 10px 10px;" />
                                        </div>
    
                                    }
                                    if (@Model[modelIndex].GeneralQuestions[questionIndex].ImagePosition == 3)
                                    {
                                        <div class="row">
                                            <img src="~/Images/@Model[modelIndex].GeneralQuestions[questionIndex].Image_Path" style=" color:white; border-width: 0; margin: 10px 10px 10px 10px;" />
                                        </div>
                                        <div class="row">
                                            <span>@indexCount - </span>
    
                                            @Html.DisplayFor(m => m[modelIndex].GeneralQuestions[questionIndex].QuestionName,
                                              new
                                              {
                                                  @class = "required noWrap form-control",
                                                  @style = "font-weight:bold; "
                                              }
                                              )
    
                                        </div>
    
                                    }
    
                                    if (@Model[modelIndex].GeneralQuestions[questionIndex].ImagePosition == 4)
                                    {
                                        <div class="row">
                                            <span>@indexCount - </span>
    
                                            @Html.DisplayFor(m => m[modelIndex].GeneralQuestions[questionIndex].QuestionName,
                                              new
                                              {
                                                  @class = "required noWrap form-control",
                                                  @style = "font-weight:bold;"
                                              }
                                              )
                                        </div>
                                        <br />
                                        <div class="row">
                                            <img src="~/Images/@Model[modelIndex].GeneralQuestions[questionIndex].Image_Path" style=" color:white; border-width: 0; margin: 10px 10px 10px 10px;" />
                                        </div>
    
                                    }
    
    
                                }
                                @if (@Model[modelIndex].GeneralQuestions[questionIndex].Image_Path == null)
                                {
                                    <span>@indexCount - </span>
                                    @Html.DisplayFor(m => m[modelIndex].GeneralQuestions[questionIndex].QuestionName,
                                    new
                                    {
                                        @class = " noWrap form-control",
                                        @style = "font-weight:bold;",
                                        @type = "radio"
                                          }
                                    )
                                }
    
                            </li>
                        </ul>
                    </div>
                    <ul class="fa-random"></ul>
                    @for (var answerIndex = 0; answerIndex < Model[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers.Count; ++answerIndex)
                    {
                        var ans = @Model[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers[answerIndex].Answer.Count;
                        var selectAnswer = @Model[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers[answerIndex];
    
                        var ans1 = @Model[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers[answerIndex].AnswerId.ToList();
                        var possibleAnswerId = item.PossibleAnswers[answerIndex];
    
                        // int  index = index +1;
                        <div class="col-md-7" style="font-family:Arial">
    
                            <label id="shuffle">
    
                                @for (int ansOption = 0; ansOption < ans; ansOption++)
                                {
                                    @*@Html.RadioButtonFor(m => m[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers,
                                Model[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers[answerIndex].AnswerId,*@
                                    @Html.RadioButtonFor(m => m[modelIndex].GeneralQuestions[questionIndex].UserSelectAnswerdId,
                                                             possibleAnswerId.AnswerId[ansOption],
                                  new
                                  {
                                      @type = "radio",
                                      @required = "required",
                                     // @id = possibleAnserId.AnswerId[ansOption],
                                       @id = "radio",
                                  }
                              )
                                    @*<span> @possibleAnswerId.AnswerId[1]</span>*@
                                    <span style="font-family: Times New Roman; font-size: 22px;">
    
                                        @Html.DisplayFor(m => m[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers[answerIndex].Answer[ansOption],
                                            new
                                            {
                                                @style = "font-weight:bold; ",
                                                @size = "25px",
                                             })
                                    </span>
    
                                    @*<span style="font-size:22px; font-family:'Times New Roman'">  @Model[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers[answerIndex] </span>*@
                                    <br />
                                    <span>   </span>
                                }
    
                            </label>
    
                        </div>
                        <br />
                    }
                </div>
            </div>
                }
                <hr />
            }
         
        </div>
    
        <div class="text-center form-group col-md-12 ">
    
            <button id="btnSave"
                    type="submit" onclick="validateAndSubmit();"
                    class=" btn btn-primary">
                FINISHED
            </button>
    
            @*<button id="btnSave" type="submit"
                        class=" btn btn-primary">
                    FINISHED
                </button>*@
        </div>
    
    
    }
     

    my model

    using System;
    using System.Collections.Generic;
    using System.Linq;
     using System.ComponentModel.DataAnnotations;
    using System.Web;
    using System.Web.Mvc;
    using BoatSafetyExam.Global;
    using BoatSafetyExam.Models;
    using BoatSafetyExam.ViewModels;
    
    namespace BoatSafetyExam.ViewModels
    {
         public class Student_Exam_ViewModel
        {
            public List<Questions> GeneralQuestions { get; set; }
        }
    
        public class Questions
        {
            [Key]
            public int QuestionId { get; set; }
            public string QuestionName { get; set; }
            //public string Question_Section { get; set; }
         
            public int? AssessmentId { get; set; }
            public string Assessment_Section { get; set; }
            public int  Amount_of_Question { get; set; }
            public int Count { get; set; }
            public string Image_Path { get; set; }
            public int? ImagePosition { get; set; }
            public List<PossibleAnswer> PossibleAnswers { get; set; }
            public int UserSelectAnswerdId { get; set; }
          
        }
          
        public class PossibleAnswer
        {
            [Key]
            public List<int> AnswerId { get; set; }
            public int? QuestionId { get; set; }
            public List<string> Answer { get; set; }
            public List<string> Answer_Options { get; set; }
     
    
        }
    
     
    }
    
    
    

    Thursday, August 6, 2020 1:56 PM

Answers

  • User1686398519 posted

    Hi luay20032003,

    You can store the data in the database. For example, you can add a table to store questionId, userId, and examId. You can query the questionId based on the studentId and examId next time.You can create fields according to your own actual needs.y

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 12, 2020 10:06 AM

All replies

  • User1686398519 posted

    Hi luay20032003,

    According to your needs, I modified your code, please refer to it.

    • You can use the session to store the necessary information.
    • There was a problem when I tested the code you provided, so I modified the model. If you have no problems, no modification is required.

    Model

     public class PossibleAnswer
     {
            [Key]
            public int AnswerId { get; set; }
            public string Answer_Options { get; set; }
            public int? QuestionId { get; set; }
            public List<int> AnswerIdList { get; set; }
            public List<string> Answer_OptionsList { get; set; }
     }

    Controller

     public ActionResult Index(string studentName, Student_Exam_ViewModel model1, int? TWRAid, DateTime? DOB,
                                        string Student_Phone_Number, int? No_of_Attempt, string errmsg, string procId, string reTake)
          {
    
                var allquestionlisttest = new List<Questions>();
                var exceptlist = new List<Questions>();
                var m1s = from A in _db.Exam_Assessment
                          select A;
                var mod = new List<Student_Exam_ViewModel>();
                reTake = "1";
                if (reTake == "1")
                {
                    if (Session["GeneralQuestions"] != null)
                    {
                        foreach (KeyValuePair<string, List<Questions>> ele in Session["GeneralQuestions"] as IDictionary<string, List<Questions>>)
                        {
                            if (ele.Key == "1")
                            {
                                exceptlist = ele.Value;
                            }
                        }
                    }
                }
                foreach (var m1 in m1s)
                {
                    var q1s = _db.Exam_Questions.Where(q => q.Assessment_Section == m1.Assessment_Section && m1.Amount_of_Test_Question > 0).ToList();
                    foreach (var q1 in q1s.Take(m1.Amount_of_Test_Question))
                    {
                        var answerId = _db.Exam_Answers.Where(x => x.QuestionId == q1.QuestionId)
                            .Select(x => x.AnswerId).ToList();
                        var answerOptions = _db.Exam_Answers.
                            Where(x => x.QuestionId == q1.QuestionId).Select(x => x.Answer_Options).ToList(); // No shuffle
    
                        var ques = new Questions
                        {
                            QuestionId = q1.QuestionId,
                            QuestionName = q1.QuestionName,
                            Assessment_Section = q1.Assessment_Section,
                            Amount_of_Question = m1.Amount_of_Test_Question,
    
                            PossibleAnswers = new List<PossibleAnswer>
                                    {
                                        new PossibleAnswer { AnswerIdList  = answerId,Answer_OptionsList = answerOptions}
    
                                    }
                        };
                        allquestionlisttest.Add(ques);
                    }
                }
                var testquesId = allquestionlisttest.Except(exceptlist,new QuestionIdComparer()).Take(2).ToList();
                var testqueslist = new List<Questions>();
                testquesId.ForEach(r =>
                {
                    allquestionlisttest.ForEach(q =>
                    {
                        if (q.QuestionId == r.QuestionId)
                        {
                            testqueslist.Add(r);
                        }
                     });
                });
               Session["reTake"] = "0";
               IDictionary<string, List<Questions>> d = new Dictionary<string, List<Questions>>();
               d.Add(new KeyValuePair<string, List<Questions>>("1", testqueslist));
               Session["GeneralQuestions"] = d;
               for (var i = 0; i < testqueslist.Count; i++)
                {
                    var model = new Student_Exam_ViewModel
                    {
                        GeneralQuestions = new List<Questions>
                            {
                                testqueslist[i]
                            }
                    };
                    mod.Add(model);
                }
               return View(mod.ToArray());
            }
        }

    Here is the result.

    Best Regards,

    YihuiSun

    Friday, August 7, 2020 10:22 AM
  • User1694748171 posted

    what's is that ?

    QuestionIdComparer()
    Monday, August 10, 2020 1:38 PM
  • User1686398519 posted

    Hi luay20032003,

    Sorry, below is the codes for the method QuestionIdComparer.

        public  class QuestionIdComparer :IEqualityComparer<Questions>
        {
            public bool Equals(Questions x, Questions y)
            {
                if (x.QuestionId== y.QuestionId)
                {
                    return true;
                }
                return false;
            }
    
            public int GetHashCode(Questions obj)
            {
                return obj.QuestionId;
            }
        }

    Best Regards,

    YihuiSun

    Tuesday, August 11, 2020 1:29 AM
  • User1694748171 posted

    Yours approach will not be work because you store the store id in a session, so what id the student want to take exam next day and the session is expired. in this case student will be have same question next time. 

    Tuesday, August 11, 2020 12:29 PM
  • User1686398519 posted

    Hi luay20032003,

    You can store the data in the database. For example, you can add a table to store questionId, userId, and examId. You can query the questionId based on the studentId and examId next time.You can create fields according to your own actual needs.y

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 12, 2020 10:06 AM