locked
Can I tied answer id to answer option when shuffle the answer while refreshing the page ? RRS feed

  • Question

  • User1694748171 posted

     I need to tied the answer Id to answers option when do shuffling the answer each time when refresh the page. 

    my code in controller 

     

     public ActionResult Index(string studentName , Student_Exam_ViewModel model1)
            {
    
                TimeSpan ts = new TimeSpan(1,30,0); //10 seconds
              
                ViewBag.Time = ts.ToString();
                 
    
                ViewBag.Name = studentName;
                Questions questions = new Questions();
                Student_Exam_ViewModel gen = new Student_Exam_ViewModel();
                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>();
                var answerOption = new List<string>();
                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();
                        foreach (var id in answerId)
                        {
                               answerOption = _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();
    
                        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 = answerOption}
                                        
                                      }
                                       }
                                  }
                            };
                            mod.Add(model);
                    }
                }
    
                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("Getdata", "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="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 class="w3-container" 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">
                                        @foreach (var x in ans1)
                                        {
                                            <span> @possibleAnswerId.AnswerId[x]</span>
                                        }
    
                                        @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</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 />
            }
            @*<p>
                    <button type="button" class="btn btn-primary small"
                            onclick="location.href = '@Url.Action("Index", "Student_Exam", new {  } )'">
                        <i class="fa fa-plus-circle"></i>
                        FINISHED
                    </button>
                </p>*@
        </div>
    
        <div class="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>
    
    
    }
    <sc

    Thursday, July 30, 2020 2:12 AM

All replies

  • User1686398519 posted

    Hi luay20032003,

    1. Since you did not give a model, I created some models based on your code, and you can modify them according to your needs.
    2. Your query process can be written more simply, if you are willing to modify it, you can refer to the code I provided.
    3. luay20032003

      @for (var modelIndex = 0; modelIndex < 3
      • The number of cycles should be less than the count of the model.
    4. You can modify the part that shows the answer options according to my code below,the Id of the answer option can be displayed after modification.
    5. Note: If you are interested in understanding how to deal with complex data models, from a certain point of view, this will help you to some extent at the current problem.

    Model

        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_Img { get; set; }
            public string Image_Path { get; set; }
            public int? Image_Position { get; set; }
            public int? Amount_of_Question { get; set; }
            public string Assessment_Section { get; set; }
            public int? AssessmentId { get; set; }
            public Exam_Assessment Exam_Assessment{ get; set; }
            public int SelectedAnswerdId { get; set; }
            public int? UserSelectAnswerdId { get; set; }
            public List<PossibleAnswer> PossibleAnswers { get; set; }
        }
    
        public class PossibleAnswer
        {
            [Key]
            public int? AnswerId { get; set; }
            public int? QuestionId { get; set; }
            public string Answer_Option { get; set; }
        }
        public class Exam_Assessment
        {
            [Key]
            public int? AssessmentId { get; set; }
            public string Assessment_Section { get; set; }
            public int Amount_of_Test_Question { get; set; }
        }

    Controller

    public ActionResult Indexwithyourcode(string StudentName, Student_Exam_ViewModel Exammodel)
            {
                Student_Exam_ViewModel gen = new Student_Exam_ViewModel();
                gen.GeneralQuestions = new List<Questions>();
                var m1s = from A in db.Exam_Assessment
                          select A;
                var mod = new List<Student_Exam_ViewModel>();
                foreach (var m1 in m1s)
                {
                    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).Take(1).ToList();
                    foreach (var q1 in q1s.Take(m1.Amount_of_Test_Question))
                    {
                        var answers = db.Exam_Answers.OrderBy(t => Guid.NewGuid()).Where(x => x.QuestionId == q1.QuestionId).OrderBy(t => Guid.NewGuid()).ToList();
                        q1.PossibleAnswers = answers;
                        gen.GeneralQuestions.Add(q1);
                    }
                }
                mod.Add(gen);
                return View(mod.ToArray());
            }

    Page(Only the modified part of the code is given.)

    @for (var modelIndex = 0; modelIndex < Model.Count(); ++modelIndex)
    {
        @*The code here has not been modified, so it is omitted.*@
        <div class="form-group">
             <div class="col-md-12">
    @*The code here has not been modified, so it is omitted.*@ @for (var answerIndex = 0; answerIndex < Model[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers.Count; ++answerIndex) { var ans = item.PossibleAnswers[answerIndex]; <div class="col-md-7" style="font-family:Arial"> <label class="noWrapform-control" style="font-family:Arial" for="@($"_{modelIndex}_.GeneralQuestions_{questionIndex}_.PossibleAnswers.AnswerId_{answerIndex}")"> @Html.HiddenFor(m => Model[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers[answerIndex].QuestionId) @Html.HiddenFor(m => Model[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers[answerIndex].AnswerId) @Html.HiddenFor(m => Model[modelIndex].GeneralQuestions[questionIndex].PossibleAnswers[answerIndex].Answer_Option) @Html.RadioButtonFor(m => Model[modelIndex].GeneralQuestions[questionIndex].UserSelectAnswerdId, ans.AnswerId, new{ @type = "radio", @class = "required", @required = "required", id = $"GeneralQuestions_{modelIndex}_.PossibleAnswers.AnswerId_{answerIndex}" }) <span> @ans.AnswerId</span> <span style="font-size:22px; font-family:'Times New Roman'"> @ans.Answer_Option </span> <br /> <span id="err" style="font-size:22px;color:red; font-family:'Times New Roman'"></span> </label> </div> <br /> } @*The code here has not been modified, so it is omitted.*@ }

    Here is the result.

    Best Regards,

    YihuiSun

    Friday, July 31, 2020 2:53 AM