QUIZ Application With ASP.NET MVC 5

Introduction

There are so many people who asked in the forums how we can build a quiz application using ASP.NET MVC. I would like to share with you a simple solution to achieve this application.

In this post, we will build our quiz application with an easy and simple approach. But you should have some basic skills in ASP.NET MVC 5, jQuery, and Bootstrap. I hope it will be helpful for you.

Prerequisites

Make sure you have installed Visual Studio 2015 (.NET Framework 4.5.2) and SQL Server.

In this post, we are going to:

  • Create Database.
  • Create MVC application.
  • Configuring Entity framework ORM to connect to the database.
  • Create our Quiz controller.
  • Create Razor pages in order to build our application.                             

SQL Database part

Here, you will find the script to create a database and tables.

Create Database

  1. USE [master]  
  2. GO  
  3.   
  4. /****** Object:  Database [DBQuiz]    Script Date: 11/18/2017 10:57:17 AM ******/  
  5. CREATE DATABASE [DBQuiz]  
  6.  CONTAINMENT = NONE  
  7.  ON  PRIMARY   
  8. NAME = N'DBQuiz', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBQuiz.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  9.  LOG ON   
  10. NAME = N'DBQuiz_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBQuiz_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  11. GO  
  12.   
  13. ALTER DATABASE [DBQuiz] SET COMPATIBILITY_LEVEL = 110  
  14. GO  
  15.   
  16. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  17. begin  
  18. EXEC [DBQuiz].[dbo].[sp_fulltext_database] @action = 'enable'  
  19. end  
  20. GO  
  21.   
  22. ALTER DATABASE [DBQuiz] SET ANSI_NULL_DEFAULT OFF   
  23. GO  
  24.   
  25. ALTER DATABASE [DBQuiz] SET ANSI_NULLS OFF   
  26. GO  
  27.   
  28. ALTER DATABASE [DBQuiz] SET ANSI_PADDING OFF   
  29. GO  
  30.   
  31. ALTER DATABASE [DBQuiz] SET ANSI_WARNINGS OFF   
  32. GO  
  33.   
  34. ALTER DATABASE [DBQuiz] SET ARITHABORT OFF   
  35. GO  
  36.   
  37. ALTER DATABASE [DBQuiz] SET AUTO_CLOSE OFF   
  38. GO  
  39.   
  40. ALTER DATABASE [DBQuiz] SET AUTO_CREATE_STATISTICS ON   
  41. GO  
  42.   
  43. ALTER DATABASE [DBQuiz] SET AUTO_SHRINK OFF   
  44. GO  
  45.   
  46. ALTER DATABASE [DBQuiz] SET AUTO_UPDATE_STATISTICS ON   
  47. GO  
  48.   
  49. ALTER DATABASE [DBQuiz] SET CURSOR_CLOSE_ON_COMMIT OFF   
  50. GO  
  51.   
  52. ALTER DATABASE [DBQuiz] SET CURSOR_DEFAULT  GLOBAL   
  53. GO  
  54.   
  55. ALTER DATABASE [DBQuiz] SET CONCAT_NULL_YIELDS_NULL OFF   
  56. GO  
  57.   
  58. ALTER DATABASE [DBQuiz] SET NUMERIC_ROUNDABORT OFF   
  59. GO  
  60.   
  61. ALTER DATABASE [DBQuiz] SET QUOTED_IDENTIFIER OFF   
  62. GO  
  63.   
  64. ALTER DATABASE [DBQuiz] SET RECURSIVE_TRIGGERS OFF   
  65. GO  
  66.   
  67. ALTER DATABASE [DBQuiz] SET  DISABLE_BROKER   
  68. GO  
  69.   
  70. ALTER DATABASE [DBQuiz] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  71. GO  
  72.   
  73. ALTER DATABASE [DBQuiz] SET DATE_CORRELATION_OPTIMIZATION OFF   
  74. GO  
  75.   
  76. ALTER DATABASE [DBQuiz] SET TRUSTWORTHY OFF   
  77. GO  
  78.   
  79. ALTER DATABASE [DBQuiz] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  80. GO  
  81.   
  82. ALTER DATABASE [DBQuiz] SET PARAMETERIZATION SIMPLE   
  83. GO  
  84.   
  85. ALTER DATABASE [DBQuiz] SET READ_COMMITTED_SNAPSHOT OFF   
  86. GO  
  87.   
  88. ALTER DATABASE [DBQuiz] SET HONOR_BROKER_PRIORITY OFF   
  89. GO  
  90.   
  91. ALTER DATABASE [DBQuiz] SET RECOVERY SIMPLE   
  92. GO  
  93.   
  94. ALTER DATABASE [DBQuiz] SET  MULTI_USER   
  95. GO  
  96.   
  97. ALTER DATABASE [DBQuiz] SET PAGE_VERIFY CHECKSUM    
  98. GO  
  99.   
  100. ALTER DATABASE [DBQuiz] SET DB_CHAINING OFF   
  101. GO  
  102.   
  103. ALTER DATABASE [DBQuiz] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  104. GO  
  105.   
  106. ALTER DATABASE [DBQuiz] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  107. GO  
  108.   
  109. ALTER DATABASE [DBQuiz] SET  READ_WRITE   
  110. GO  

Create Tables

After creating the database, we will move to create all the needed tables.

Users Table

  1. USE [DBQuiz]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Users]    Script Date: 11/18/2017 10:58:08 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[Users](  
  15.     [UserID] [int] IDENTITY(1,1) NOT NULL,  
  16.     [FullName] [varchar](50) NULL,  
  17.     [ProfilImage] [varchar](50) NULL,  
  18.  CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED   
  19. (  
  20.     [UserID] ASC  
  21. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  22. ON [PRIMARY]  
  23.   
  24. GO  
  25.   
  26. SET ANSI_PADDING OFF  
  27. GO  

Quiz Table

  1. USE [DBQuiz]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Quiz]    Script Date: 11/18/2017 10:58:43 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[Quiz](  
  15.     [QuizID] [int] IDENTITY(1,1) NOT NULL,  
  16.     [QuizName] [varchar](80) NULL,  
  17.  CONSTRAINT [PK_Quiz] PRIMARY KEY CLUSTERED   
  18. (  
  19.     [QuizID] ASC  
  20. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  21. ON [PRIMARY]  
  22.   
  23. GO  
  24.   
  25. SET ANSI_PADDING OFF  
  26. GO  

Questions Table

  1. USE [DBQuiz]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Questions]    Script Date: 11/18/2017 10:59:29 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[Questions](  
  15.     [QuestionID] [int] IDENTITY(1,1) NOT NULL,  
  16.     [QuestionText] [varchar](maxNULL,  
  17.     [QuizID] [intNULL,  
  18.  CONSTRAINT [PK_Questions] PRIMARY KEY CLUSTERED   
  19. (  
  20.     [QuestionID] ASC  
  21. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  22. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  23.   
  24. GO  
  25.   
  26. SET ANSI_PADDING OFF  
  27. GO  
  28.   
  29. ALTER TABLE [dbo].[Questions]  WITH CHECK ADD  CONSTRAINT [FK_Questions_Quiz] FOREIGN KEY([QuizID])  
  30. REFERENCES [dbo].[Quiz] ([QuizID])  
  31. GO  
  32.   
  33. ALTER TABLE [dbo].[Questions] CHECK CONSTRAINT [FK_Questions_Quiz]  
  34. GO  

Choices Table

  1. USE [DBQuiz]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Choices]    Script Date: 11/18/2017 11:00:03 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[Choices](  
  15.     [ChoiceID] [int] IDENTITY(1,1) NOT NULL,  
  16.     [ChoiceText] [varchar](maxNULL,  
  17.     [QuestionID] [intNULL,  
  18.  CONSTRAINT [PK_Choices] PRIMARY KEY CLUSTERED   
  19. (  
  20.     [ChoiceID] ASC  
  21. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  22. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  23.   
  24. GO  
  25.   
  26. SET ANSI_PADDING OFF  
  27. GO  
  28.   
  29. ALTER TABLE [dbo].[Choices]  WITH CHECK ADD  CONSTRAINT [FK_Choices_Questions] FOREIGN KEY([QuestionID])  
  30. REFERENCES [dbo].[Questions] ([QuestionID])  
  31. GO  
  32.   
  33. ALTER TABLE [dbo].[Choices] CHECK CONSTRAINT [FK_Choices_Questions]  
  34. GO  

Answers Table

  1. USE [DBQuiz]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Answers]    Script Date: 11/18/2017 11:00:46 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[Answers](  
  15.     [AnswerID] [int] IDENTITY(1,1) NOT NULL,  
  16.     [AnswerText] [varchar](maxNULL,  
  17.     [QuestionID] [intNULL,  
  18.  CONSTRAINT [PK_Answers] PRIMARY KEY CLUSTERED   
  19. (  
  20.     [AnswerID] ASC  
  21. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  22. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  23.   
  24. GO  
  25.   
  26. SET ANSI_PADDING OFF  
  27. GO  
  28.   
  29. ALTER TABLE [dbo].[Answers]  WITH CHECK ADD  CONSTRAINT [FK_Answers_Questions] FOREIGN KEY([QuestionID])  
  30. REFERENCES [dbo].[Questions] ([QuestionID])  
  31. GO  
  32.   
  33. ALTER TABLE [dbo].[Answers] CHECK CONSTRAINT [FK_Answers_Questions]  
  34. GO  

Create your MVC application

Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.

QUIZ Application With ASP.NET

Next, a new dialog will pop up for selecting the template. We are going to choose MVC template and click OK.

QUIZ Application With ASP.NET

Once our project is created, let us add ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

Right-click on the project name, click Add >> Add New Item.

A dialog box will pop up. Inside Visual C#, select Data >> ADO.NET Entity Data Model, and enter the name for your DbContext model as Quizz, then click Add.

QUIZ Application With ASP.NET

As you can see, we have 4 model contents. We are selecting the first approach (EF Designer from database).

QUIZ Application With ASP.NET

As you can see below, we need to select the server name, then via drop-down list in the "connect to a database" section. You must choose your database name and finally click OK.

QUIZ Application With ASP.NET

For the next step, the dialog Entity Data Model Wizard will pop up for choosing objects which will be used in our application. We are selecting all the tables except sysdiagrams and click Finish.

Finally, we see that EDMX model generates all the objects, as shown below.

QUIZ Application With ASP.NETQUIZ Application With ASP.NET
Create a controller

Now, we are going to create a Controller. Right-click the Controllers folder, go to Add >> Controller>> MVC 5 Controller - Empty>> click Add. In the next dialog, name the controller as QuizzController and then click Add.

QUIZ Application With ASP.NET

QUIZ Application With ASP.NET

QuizzController.cs

User needs to be authenticated by providing her/his full name, then if the user already exists in users table, we will redirect him to select the quiz via the dropdown list and if not, message will be displayed 'Sorry: user is not found'. The responsible action is GetUser action.

  1. [HttpGet]  
  2.  public ActionResult GetUser()  
  3.  {  
  4.      return View();  
  5.  }  
  6.   
  7.  [HttpPost]  
  8.  public ActionResult GetUser(UserVM user)  
  9.  {  
  10.      UserVM userConnected = dbContext.Users.Where(u => u.FullName == user.FullName)  
  11.                                   .Select(u => new UserVM  
  12.                                      {  
  13.                                          UserID = u.UserID,  
  14.                                          FullName = u.FullName,  
  15.                                          ProfilImage = u.ProfilImage,  
  16.   
  17.                                      }).FirstOrDefault();  
  18.   
  19.      if(userConnected != null)  
  20.      {  
  21.          Session["UserConnected"] = userConnected;  
  22.          return RedirectToAction("SelectQuizz");  
  23.      }  
  24.      else  
  25.      {  
  26.          ViewBag.Msg = "Sorry : user is not found !!";  
  27.          return View();  
  28.      }  
  29.   
  30.  }  

GetUser.cshtml

  1. @model QuizApplicationMVC5.viewModels.UserVM  
  2.   
  3. @{  
  4.     ViewBag.Title = "User";  
  5. }  
  6.   
  7. <div class="panel panel-default" style="width: 37%; margin: 20% 32%;">  
  8.     <div class="panel-heading">Let's Begin  ^_^</div>  
  9.     <div class="panel-body">  
  10.   
  11.         @using (Html.BeginForm("GetUser""Quizz", FormMethod.Post))  
  12.         {  
  13.             @Html.EditorFor(c => c.FullName, new { htmlAttributes = new { @class = "form-control", @placeholder = "FullName ...", @style= "width:100%; margin-left: 56px;" }  } )<br/>  
  14.             <button type="submit" id="Enter" class="btn btn-info btn-lg" style="width:100%;"><span class="glyphicon glyphicon-user"></span>   Enter</button>  
  15.         }  
  16.   
  17.     </div>  
  18.   
  19.     @if (ViewBag.Msg != null)  
  20.     {  
  21.         <div class="well well-sm well-danger"> @ViewBag.Msg </div>  
  22.     }  
  23. </div>  

Select Quiz [HttpGet]  action is responsible for getting the list of quiz name from quiz table and display them into SelectQuizz.cshtml page.

Select Quiz [HttpPost]  action accepts quiz object as parameter which contains the selected quiz, and after that, we will redirect the authenticated user to quiz test action which will display all the questions related to the selected quiz.

  1. [HttpGet]  
  2. public ActionResult SelectQuizz()  
  3. {  
  4.     QuizVM quiz = new viewModels.QuizVM();  
  5.     quiz.ListOfQuizz = dbContext.Quizs.Select(q => new SelectListItem  
  6.     {  
  7.         Text = q.QuizName,  
  8.         Value = q.QuizID.ToString()  
  9.   
  10.     }).ToList();  
  11.   
  12.     return View(quiz);  
  13. }  
  14.   
  15. [HttpPost]  
  16. public ActionResult SelectQuizz(QuizVM quiz)  
  17. {  
  18.     QuizVM quizSelected = dbContext.Quizs.Where(q => q.QuizID == quiz.QuizID).Select(q => new QuizVM  
  19.     {  
  20.         QuizID = q.QuizID,  
  21.         QuizName = q.QuizName,  
  22.   
  23.     }).FirstOrDefault();  
  24.   
  25.     if(quizSelected != null)  
  26.     {  
  27.         Session["SelectedQuiz"] = quizSelected;  
  28.   
  29.         return RedirectToAction("QuizTest");  
  30.     }  
  31.   
  32.     return View();  
  33. }  

SelectQuizz.cshtml

  1. @model QuizApplicationMVC5.viewModels.QuizVM  
  2.   
  3. @{  
  4.     ViewBag.Title = "SelectQuizz";  
  5. }  
  6.   
  7. <div class="container">  
  8.   
  9.     <div class="userConnected" style="border:2px dashed #cecaca; border-radius: 10px; margin-top: 3%;">  
  10.   
  11.         @{ Html.RenderPartial("_UserInfo");}  
  12.   
  13.     </div>  
  14.   
  15.   
  16.     <div class="SelQuiz">  
  17.   
  18.         <div class="panel panel-default" style="width: 37%; margin: 20% 32%;">  
  19.             <div class="panel-heading">Select Your Quiz  ^_^</div>  
  20.             <div class="panel-body">  
  21.   
  22.                 @using (Html.BeginForm("SelectQuizz""Quizz", FormMethod.Post))  
  23.                 {  
  24.                     @Html.DropDownListFor(model => model.QuizID, Model.ListOfQuizz, new { @class = "form-control", @style = "margin-left:51px;" } )<br/>  
  25.                     <button type="submit" id="Enter" class="btn btn-success btn-lg" style="width:100%;"><span class="glyphicon glyphicon-ok"></span>   Let's GO </button>  
  26.                 }  
  27.   
  28.             </div>  
  29.         </div>  
  30.   
  31.     </div>  
  32.   
  33. </div>  <!-- END CONTAINER -->  

As you can see, QuizTest [HttpGet] action will display all the questions based on the selected quiz.

QuizTest [HttpPost] action accepts answers list as a parameter, then it will proceed to verify all the answers submitted by the user and returns the result in JSON format.

  1. [HttpGet]  
  2. public ActionResult QuizTest()  
  3. {  
  4.     QuizVM quizSelected = Session["SelectedQuiz"] as QuizVM;  
  5.     IQueryable<QuestionVM> questions = null;  
  6.   
  7.     if (quizSelected != null)  
  8.     {  
  9.          questions = dbContext.Questions.Where(q => q.Quiz.QuizID == quizSelected.QuizID)  
  10.             .Select(q => new QuestionVM  
  11.             {  
  12.                 QuestionID = q.QuestionID,  
  13.                 QuestionText = q.QuestionText,  
  14.                 Choices = q.Choices.Select(c => new ChoiceVM {  
  15.                     ChoiceID = c.ChoiceID,  
  16.                     ChoiceText = c.ChoiceText  
  17.                 }).ToList()  
  18.   
  19.             }).AsQueryable();  
  20.   
  21.   
  22.     }  
  23.   
  24.     return View(questions);  
  25. }  
  26.   
  27. [HttpPost]  
  28. public ActionResult QuizTest(List<QuizAnswersVM> resultQuiz)  
  29. {  
  30.     List<QuizAnswersVM> finalResultQuiz = new List<viewModels.QuizAnswersVM>();  
  31.   
  32.     foreach(QuizAnswersVM answser in resultQuiz)  
  33.     {  
  34.         QuizAnswersVM result = dbContext.Answers.Where(a => a.QuestionID == answser.QuestionID).Select(a => new QuizAnswersVM  
  35.         {  
  36.             QuestionID = a.QuestionID.Value,  
  37.             AnswerQ = a.AnswerText,  
  38.             isCorrect = (answser.AnswerQ.ToLower().Equals(a.AnswerText.ToLower()))  
  39.   
  40.         }).FirstOrDefault();  
  41.   
  42.         finalResultQuiz.Add(result);  
  43.     }  
  44.   
  45.     return Json(new { result = finalResultQuiz }, JsonRequestBehavior.AllowGet);  
  46. }  

QuizTest.cshtml

  1. @model IQueryable<QuizApplicationMVC5.viewModels.QuestionVM>  
  2.   
  3. @{   
  4.     int count = 1, countR = 0;  
  5. }  
  6.   
  7.   
  8. <div class="container">  
  9.   
  10.    <!-- User Info -->  
  11.     <div class="userConnected" style="border:2px dashed #cecaca; border-radius: 10px; margin-top: 3%;">  
  12.   
  13.         @{ Html.RenderPartial("_UserInfo");}  
  14.   
  15.     </div>  
  16.   
  17.     <div class="Quiz">  
  18.   
  19.         <h4 style="margin-top: 4%;"> <span class="label label-info">Questions :</span> </h4>  
  20.   
  21.       @if (Model != null && Model.Any())  
  22.       {  
  23.   
  24.               foreach (var question in Model)  
  25.               {  
  26.                 <div class="BlockQ" style="border: 1px solid #bdbdbd; width: 75%; border-radius: 4px; margin-top: 40px; background-color: #f0ffff; padding: 8px;">  
  27.   
  28.                     <div class="Question" style="padding: 2%;">  
  29.                         <span class="label label-warning"> @string.Format("{0}{1}.""Q", count)</span>  
  30.                         <span id="@string.Format("{0}{1}", "ID_Q", count)" style="display:none;">@question.QuestionID</span>  
  31.                         <p style="display: inline; padding: 2%;" id="@string.Format("{0}{1}", "Q", count)">@question.QuestionText</p>  
  32.                     </div>  
  33.   
  34.                     <div class="Choices" style="margin-left: 8%;">  
  35.   
  36.                         @foreach (var choice in question.Choices)  
  37.                         {  
  38.                                 <label class="radio-inline">  
  39.                                     <input type="radio" name="@string.Format("{0}{1}", "inlineRadioOptions",count)" id="@string.Format("{0}{1}", "inlineRadio", countR)" value="@choice.ChoiceText" style="margin-left: -16px;"> @choice.ChoiceText  
  40.                                 </label><br />  
  41.                             countR++;  
  42.                         }  
  43.   
  44.                     </div> <!--END Choices-->  
  45.                    
  46.                 <div id="@string.Format("{0}{1}{2}", "Ans","Q", count)">  
  47.   
  48.   
  49.                 </div>  
  50.   
  51.                 </div> <!-- END BlockQ -->  
  52.                   count++;  
  53.               }  
  54.             <span id="countQuections" style="display:none;">@count</span>  
  55.             <button type="button" id="SubmitQuiz" class="btn btn-default" style="margin-top: 10px;"><span class="glyphicon glyphicon-ok"></span>   Submit Quiz </button>  
  56.         
  57.   
  58.       }  
  59.   
  60.     </div> <!-- END QUIZ -->  
  61.   
  62. </div> <!-- END CONTAINER -->  
  63.   
  64. @section MyScritps  
  65. {  
  66.     <script type="text/javascript">  
  67.   
  68.         $(document).ready(function () {  
  69.   
  70.             $('#SubmitQuiz').on('click'function () {  
  71.   
  72.                 //count Questions  
  73.                 var sel = $('#countQuections').text();  
  74.   
  75.                 console.log(sel);  
  76.   
  77.                 var resultQuiz = [], countQuestion = parseInt(sel), question = {}, j = 1;  
  78.   
  79.                 for (var i = 1; i < countQuestion; i++) {  
  80.                     question = {  
  81.                         QuestionID: $('#ID_Q'+ i).text(),  
  82.                         QuestionText: $('#Q' + i).text(),  
  83.                         AnswerQ: $('input[name=inlineRadioOptions' + i + ']:checked').val()  
  84.                     }  
  85.   
  86.                     resultQuiz.push(question);  
  87.                 }  
  88.   
  89.                 $.ajax({  
  90.   
  91.                     type: 'POST',  
  92.                     url: '@Url.Action("QuizTest", "Quizz")',  
  93.                     data: { resultQuiz },  
  94.   
  95.                     success: function (response) {  
  96.   
  97.                         if (response.result.length > 0)  
  98.                         {  
  99.                             for(var i = 0; i <response.result.length; i++ )  
  100.                             {  
  101.                                 if(response.result[i].isCorrect == true)  
  102.                                 {  
  103.   
  104.                                     $('#AnsQ' + j).html('<div class="alert alert-success" role="alert"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> Correct answer</div>');  
  105.                                 }  
  106.                                 else  
  107.                                 {  
  108.                                     $('#AnsQ' + j).html('<div class="alert alert-danger" role="alert"> <span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span> Incorrect answer - The Good Answer is <b>' + response.result[i].AnswerQ + '</b></div>');  
  109.                                 }  
  110.                                 j++;  
  111.                             }  
  112.                         }  
  113.                         else  
  114.                         {  
  115.                             alert("Something Wrong");  
  116.                         }  
  117.   
  118.   
  119.                         //console.log(response.result.length);  
  120.   
  121.                     },  
  122.                     error: function (response) {  
  123.   
  124.                     }  
  125.                 });  
  126.   
  127.                 console.log(resultQuiz);  
  128.   
  129.             });  
  130.   
  131.   
  132.   
  133.         });  
  134.   
  135.     </script>  
  136. }  

View Model

Don’t forget to add the following view models.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace QuizApplicationMVC5.viewModels  
  8. {  
  9.     public class UserVM  
  10.     {  
  11.         public int UserID { get; set; }  
  12.         public string FullName { get; set; }  
  13.         public string ProfilImage { get; set; }  
  14.     }  
  15.   
  16.     public class QuizVM  
  17.     {  
  18.         public int QuizID { get; set; }  
  19.         public string QuizName { get; set; }  
  20.         public List<SelectListItem> ListOfQuizz { get; set; }  
  21.   
  22.     }  
  23.   
  24.     public class QuestionVM  
  25.     {  
  26.         public int QuestionID { get; set; }  
  27.         public string QuestionText { get; set; }  
  28.         public string QuestionType { get; set; }  
  29.         public string Anwser { get; set; }  
  30.         public  ICollection<ChoiceVM> Choices { get; set; }  
  31.     }  
  32.   
  33.     public class ChoiceVM  
  34.     {  
  35.         public int ChoiceID { get; set; }  
  36.         public string ChoiceText { get; set; }  
  37.     }  
  38.   
  39.     public class QuizAnswersVM  
  40.     {  
  41.         public int QuestionID { get; set; }  
  42.         public string QuestionText { get; set; }  
  43.         public string AnswerQ { get; set; }  
  44.         public bool isCorrect { get; set; }  
  45.   
  46.   
  47.     }  

Shared/_UserInfo.cshtml

We need to display the user detail which will be shared in SelectQuizz.cshtml and QuizzTest.cshtml. To do that, from the Solution Explorer, expand Views folder, right click on Shared folder >> Add >> View. Don’t forget to check Create as a partial view option.

  1. @using QuizApplicationMVC5.viewModels  
  2. @{  
  3.     UserVM userConnected = Session["UserConnected"] as UserVM;  
  4.     QuizVM quizSelected = Session["SelectedQuiz"] as QuizVM;  
  5.   
  6. }  
  7.   
  8.   
  9.     @if (userConnected != null)  
  10.     {  
  11.         <div class="row">  
  12.   
  13.             <div class="col-md-4">  
  14.                 <img src="@string.Format("{0}{1}", Url.Content("~/images/"), userConnected.ProfilImage)" class="img-circle" style="width: 12%;" />  
  15.                 <span> <b>Welcome :</b> @userConnected.FullName</span>  
  16.             </div>  
  17.   
  18.             <div class="col-md-4" style="margin-top: 15px;">  
  19.   
  20.                 @if ( quizSelected != null && !string.IsNullOrEmpty(quizSelected.QuizName))  
  21.                 {  
  22.                     <span> <b>Quiz Selected :</b> @quizSelected.QuizName</span>  
  23.                 }  
  24.                 else  
  25.                 {  
  26.                     <span> <b>Please Select your Quiz </b></span>  
  27.                 }  
  28.   
  29.             </div>  
  30.   
  31.             <div class="col-md-4" style="margin-top: 15px;">  
  32.                 <span> <b>Date :</b> @DateTime.Now</span>  
  33.             </div>  
  34.   
  35.         </div>  
  36.     } 

Output

Now, our quiz application is ready. We can run and see the output in the browser.

QUIZ Application With ASP.NET

That’s all. Please send your feedback and queries in the comments box. 

Up Next
    Ebook Download
    View all
    Learn
    View all