Kindly view my YouTube Video Link to learn about MY EASY KIDS LEARN using MVC.
What is EASY KIDS LEARN?
This is a Kids Easy Learn Game. Here we display 10 questions, and in each question, we will display one image and also we will display the hint for each question. Kids need to enter the correct spelling for each image displayed, For example, we display an image as 10 and kids need to enter the correct word spelling as "TEN." All the images, hint questions, and answer will be posted by the admin. The admin can add any number of images with hint questions and answers for the users (here users are kids) each time the 10 questions are randomly displayed. Using this application kids can easily learn the spelling of words.
This application has two modules:
- Admin Module
- User Module
Admin Module:
User Module:
Before starting this article kindly go through my previous article ASP.NET MVC 5 Security and Creating User Role. It explains in detail about ASP.NET Identity and creating User Role.
In this article we will see how to create and manage a question by admin and users to play game using ASP.NET MVC, WEB API and AngularJS.
Here we will see,
- Easy Kids Question Management (Only Admin user can View All / Create /Delete and Edit Questions).
- How users can play the game from home page by entering their name.
Prerequisites
Visual Studio 2015: You can download it from here.
Code part
Create Database and Table
1. Create Database and Table
We will create a KidsLearnerMaster table under the Database ‘KidsLearnerDB. The following is the script to create a database, table and sample insert query. Run this script in your SQL Server. I have used SQL Server 2014.
- -- =============================================
- -- Author : Shanu
- -- Create date : 2016-02-28
- -- Description : To Create Database
- -- =============================================
- --Script to create DB,Table and sample Insert data
- USE MASTER;
- -- 1) Check for the Database Exists .If the database is exist then drop and create new DB
- IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'KidsLearnerDB' )
- BEGIN
- ALTER DATABASE KidsLearnerDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
- DROP DATABASE KidsLearnerDB ;
- END
- CREATE DATABASE KidsLearnerDB
- GO
- USE KidsLearnerDB
- GO
- IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'kidsLearnerMaster' )
- DROP TABLE MenuMaster
- GO
- CREATE TABLE kidsLearnerMaster
- (
- KIDIDENTITY int identity(1,1),
- IMAGENAME VARCHAR(200) NOT NULL,
- ANSWER VARCHAR(100) NOT NULL ,
- HINTQUESTION VARCHAR(200) NOT NULL ,
- CONSTRAINT [PK_MenuMaster] PRIMARY KEY CLUSTERED
- (
- [kidIdentity] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- select * from kidsLearnerMaster
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values('one.png','ONE','Its a Number this is the First Number')
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values('TWO.png','TWO','Its a Number with 3 Character')
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values('THREE.png','THREE','Its a Number with 5 Character')
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values('FOUR.png','FOUR','Its a Number with 4 Character')
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values('FIVE.png','FIVE','Its a Number with 4 Character')
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values('SIX.png','SIX','Its a Number with 3 Character')
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values('SEVEN.png','SEVEN','Its a Number with 5 Character')
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values('EIGHT.png','EIGHT','Its a Number and this number plus 2 is 10')
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values('NINE.png','NINE','Its a Number and 10 minus 1 is this number')
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values('TEN.png','TEN','Its a Number with 3 Character')
All these 10 default images have been uploaded to my root folder /Images. You can add more questions and images directly using the application.
Stored Procedure : Run all this Procedure one by one in your SQL Server. SP to select all records to display for Admin.
- USE KidsLearnerDB
- GO
- -- 2) select all kidsLearnerMaster records
- -- Author : Shanu
- -- Create date : 2016-02-28
- -- Description :select top 10 random kidsLearnerMaster records
- -- Tables used : kidsLearnerMaster
- -- Modifier : Shanu
- -- Modify date : 2016-02-28
- -- =============================================
- -- To Select all user roles
- -- EXEC USP_KIDSLEARN_SelectALL ''
- -- =============================================
- CREATE PROCEDURE [dbo].[USP_KIDSLEARN_SelectALL]
- (
- @IMAGENAME VARCHAR(100) = ''
- )
- AS
- BEGIN
- SELECT
- KIDIDENTITY,IMAGENAME,ANSWER,HINTQUESTION
- FROM kidsLearnerMaster
- WHERE
- IMAGENAME like @IMAGENAME +'%'
- END
SP to select top 10 Random records to display for users to play the game.
- USE KidsLearnerDB
- GO
- -- 1) select top 10 random kidsLearnerMaster records
- -- Author : Shanu
- -- Create date : 2016-02-28
- -- Description :select top 10 random kidsLearnerMaster records
- -- Tables used : kidsLearnerMaster
- -- Modifier : Shanu
- -- Modify date : 2016-02-28
- -- =============================================
- -- To Select all user roles
- -- EXEC USP_KIDSLEARN_Select ''
- -- =============================================
- CREATE PROCEDURE [dbo].[USP_KIDSLEARN_Select]
- (
- @IMAGENAME VARCHAR(100) = ''
- )
- AS
- BEGIN
- SELECT TOP 10
- KIDIDENTITY,IMAGENAME,ANSWER,HINTQUESTION
- FROM kidsLearnerMaster
- WHERE
- IMAGENAME like @IMAGENAME +'%'
- ORDER BY NEWID()
- END
- USE KidsLearnerDB
- GO
- -- 3) Insert records
- -- Author : Shanu
- -- Create date : 2016-02-28
- -- Description :Insert kidsLearnerMaster records
- -- Tables used : kidsLearnerMaster
- -- Modifier : Shanu
- -- Modify date : 2016-02-28
- -- =============================================
- -- To Select all user roles
- -- EXEC USP_KIDSLEARN_Insert ''
- -- =============================================
- CREATE PROCEDURE [dbo].[USP_KIDSLEARN_Insert]
- (
- @IMAGENAME VARCHAR(100) = '',
- @ANSWER VARCHAR(100) = '',
- @HINTQUESTION VARCHAR(200) = ''
- )
- AS
- BEGIN
- IF NOT EXISTS (SELECT * FROM kidsLearnerMaster WHERE IMAGENAME=@IMAGENAME)
- BEGIN
- Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
- values(@IMAGENAME,@ANSWER,@HINTQUESTION)
- Select 'Inserted' as results
- END
- ELSE
- BEGIN
- Select 'Exists' as results
- END
- END
- USE KidsLearnerDB
- GO
- -- 4) Update kidsLearnerMaster records
- -- Author : Shanu
- -- Create date : 2016-02-28
- -- Description :Update kidsLearnerMaster records
- -- Tables used : kidsLearnerMaster
- -- Modifier : Shanu
- -- Modify date : 2016-02-28
- -- =============================================
- -- To Select all user roles
- -- EXEC USP_KIDSLEARN_Update ''
- -- =============================================
- ALTER PROCEDURE [dbo].[USP_KIDSLEARN_Update]
- ( @KIDIDENTITY VARCHAR(20) = '',
- @IMAGENAME VARCHAR(100) = '',
- @ANSWER VARCHAR(100) = '',
- @HINTQUESTION VARCHAR(200) = ''
- )
- AS
- BEGIN
- IF EXISTS (SELECT * FROM kidsLearnerMaster WHERE KIDIDENTITY=@KIDIDENTITY)
- BEGIN
- UPDATE kidsLearnerMaster SET
- IMAGENAME=@IMAGENAME,
- ANSWER=@ANSWER,
- HINTQUESTION=@HINTQUESTION
- WHERE
- KIDIDENTITY=@KIDIDENTITY
- Select 'updated' as results
- END
- ELSE
- BEGIN
- Select 'Not Exists' as results
- END
- END
- USE KidsLearnerDB
- GO
- -- 5) Stored procedure To Delete KIDSLEARN
- -- Author : Shanu
- -- Create date : 2016-02-28
- -- Description :To Delete KIDSLEARN detail
- -- Tables used : kidsLearnerMaster
- -- Modifier : Shanu
- -- Modify date : 2016-02-28
- -- =============================================
- -- To delete KIDSLEARN record
- -- =============================================
- Create PROCEDURE [dbo].[USP_KIDSLEARN_Delete]
- ( @KIDIDENTITY VARCHAR(20) = '' )
- AS
- BEGIN
- DELETE FROM kidsLearnerMaster WHERE KIDIDENTITY=@KIDIDENTITY
- END
After installing Visual Studio 2015 click Start, then Programs, and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and then select ASP.NET Web Application. Enter your project name and click OK.


Web.Config
In web.config file we can find the DefaultConnection Connection string. By default ASP.NET MVC will use this
connection string to create all ASP.NET Identity related tables like
AspNetUsers, etc. For our application we also need to use the database for other
page activities instead of using two different databases, one for User details
and one for our own functionality. Here I will be using one database where all
ASP.NET Identity tables will be created and also we can create our own tables
for other page uses.
Here in connection string change your SQL Server Name, UID and PWD to create and store all user details in one database.
- <connectionStrings>
- <add name="DefaultConnection" connectionString="data source=YOURSERVERNAME;initial catalog= KidsLearnerDB;user id=UID;password=PWD;Integrated Security=True" providerName="System.Data.SqlClient" />
- </connectionStrings>
Firstly, create default user role like “Admin” and also we will create a default admin user. We will be creating all default roles and user in “Startup.cs”

OWIN (OPEN WEB Interface for .NET) defines a standard interface between .NET and WEB Server and each OWIN application has a Startup Class where we can specify components.
Reference
In “Startup.cs” file we can find the Configuration method. From this method we will be calling our createRolesandUsers() method to create a default user role and user. We will check for Roles already created or not. If Roles, like Admin, is not created, then we will create a new Role as “Admin” and we will create a default user and set the user role as Admin. We will be using this user as super user where the user can Manage Question from our MVC application.
- public void Configuration(IAppBuilder app)
- {
- ConfigureAuth(app);
- createRolesandUsers();
- }
- // In this method we will create default User roles and Admin user for login
- private void createRolesandUsers()
- {
- ApplicationDbContext context = new ApplicationDbContext();
- var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
- var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
- // In Startup iam creating first Admin Role and creating a default Admin User
- if (!roleManager.RoleExists("Admin"))
- {
- // first we create Admin rool
- var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
- role.Name = "Admin";
- roleManager.Create(role);
- //Here we create a Admin super user who will maintain the website
- var user = new ApplicationUser();
- user.UserName = "[email protected]";
- user.Email = "[email protected]";
- string userPWD = "A@Z200711";
- var chkUser = UserManager.Create(user, userPWD);
- //Add default User to Role Admin
- if (chkUser.Succeeded)
- {
- var result1 = UserManager.AddToRole(user.Id, "Admin");
- }
- }
- }
When we run our application we can see new default ASP.NET user related tables will be created in our KidsLearnerDB Database.
Right click our
project and click Add, then New Item. Select Data, then ADO.NET
Entity Data Model and give the name for our EF and click,

Select "EF Designer from database" and click Next.



Click finish.
Procedure
to add our Web API Controller
Right-click the Controllers
folder, click Add and then click Controller.
Select Web API 2 Controller – Empty, click add and give name for our WEB API controller.
Working with WEBAPI Controller for CRUD
Select
Controller and add an Empty Web API 2 Controller. Provide your name to the Web
API controller and click OK. Here for my Web API Controller I have given the
name “KIDSLEARNAPIController." As we have created Web API controller, we can see our controller has been
inherited with ApiController. As we all know Web API is a simple and easy way to build HTTP Services for
Browsers and Mobiles.
Web API has the following four methods as Get/Post/Put and Delete where:
- Get is to request for thedata. (Select)
- Post is to create a data.(Insert)
- Put is to update the data.
- Delete is to delete data.
Get Method
In our example I have used only a Get method since I am using only a Stored
Procedure. We need to create an object for our Entity and write our Get Method
to do Select/Insert/Update and Delete operations.
Select Operation
We use a get method to get all the details of the KidslearnMasters table
using an entity object and we return the result as IEnumerable. We use this
method in our AngularJS and display the result in an MVC page from the
AngularJS controller. Using Ng-Repeat we can bind the details.
Here we can see in the getKIDSLEARNSelect method I have passed the search
parameter to the USP_KIDSLEARN_Select ALL Stored Procedure. In the Stored
Procedure I used like "%" to return all the records if the search
parameter is empty.
- // to Search all Kids learn Details
- [HttpGet]
- public IEnumerable<USP_KIDSLEARN_SelectALL_Result> getKIDSLEARNSelectALL(string IMAGENAME)
- {
- if (IMAGENAME == null)
- IMAGENAME = "";
- return objapi.USP_KIDSLEARN_SelectALL(IMAGENAME).AsEnumerable();
- }
Next we have one more select method. This Method will be used to display top 10 random questions to users.
- // To select top 10 random results
- [HttpGet]
- public IEnumerable<USP_KIDSLEARN_Select_Result> getKIDSLEARNSelect(string IMAGENAME)
- {
- if (IMAGENAME == null)
- IMAGENAME = "";
- return objapi.USP_KIDSLEARN_Select(IMAGENAME).AsEnumerable();
- }
Insert Operation
The same as select, we passed all the parameters to the insert procedure. This insert method will return the result from the database if a record is inserted or not. We will get the result and display it from the AngularJS Controller to MVC application.
- // To insertKIDSLEARN
- [HttpGet]
- public IEnumerable<string> insertKIDSLEARN(string IMAGENAME, string ANSWER, string HINTQUESTION)
- {
- return objapi.USP_KIDSLEARN_Insert(IMAGENAME, ANSWER, HINTQUESTION).AsEnumerable();
- }
Update Operation
The same as insert, we have passed all the parameters to the Update procedure. This Update method will return the result from the database if a record is updated or not.
- //to Update updateKIDSLEARN
- [HttpGet]
- public IEnumerable<string> updateKIDSLEARN(string kidsIdentity, string IMAGENAME, string ANSWER, string HINTQUESTION)
- {
- return objapi.USP_KIDSLEARN_Update(kidsIdentity, IMAGENAME, ANSWER, HINTQUESTION).AsEnumerable();
- }
Delete Operation
The same as insert, we have passed all the parameters to the Delete procedure. This Delete method will return the result from the database as a record is delete or not.
- //to Update deleteKIDSLEARN
- [HttpGet]
- public string deleteKIDSLEARN(string kidsIdentity)
- {
- objapi.USP_KIDSLEARN_Delete(kidsIdentity);
- objapi.SaveChanges();
- return "deleted";
- }
In admin module, the Admin can be logged in and manage all Kids Question details.

Creating AngularJS Controller
Firstly, create
a folder inside the Scripts folder and we have given the folder name “MyAngular.”

Right click the MyAngular folder and click Add and New Item. Select Web
and then AngularJS Controller and provide a name for the Controller.
I have named my AngularJS Controller “Controller.js”.

Once the AngularJS Controller is created, we can see by default the controller will have the code with the default module definition and all.
If the AngularJS
package is missing, then add the package to your project.
Right click your MVC project and click Manage
NuGet Packages. Search for AngularJS and click Install.

Modules.js: Here we will add the reference to the
AngularJS JavaScript and create an Angular Module named “AngularJs_Module”.
- // <reference path="../angular.js" />
- /// <reference path="../angular.min.js" />
- /// <reference path="../angular-animate.js" />
- /// <reference path="../angular-animate.min.js" />
- var app;
- (function () {
- app = angular.module("AngularJs_Module", ['ngAnimate']);
- })();
Controllers: In AngularJS Controller I have done all the business logic and returned the data from Web API to our MVC HTML page.
Variable declarations: Firstly, we declared all the local variables which need to be used.
- app.controller("AngularJs_Controller", function ($scope, $timeout, $rootScope, $window, $http, FileUploadService) {
- $scope.date = new Date();
- $scope.MyName = "shanu";
- $scope.sImage = "";
- $scope.showKidsAdd = true;
- $scope.addEditKids = false;
- $scope.KidsList = true;
- $scope.showItem = true;
- $scope.userRoleName = $("#txtuserRoleName").val();
- //This variable will be used for Insert/Edit/Delete Kids Learn Question details. $scope.kidsIdentitys = 0;
- $scope.UImage = "";
- $scope.Answer = "";
- $scope.Question = "";
Methods
Select Method
The final result will be displayed to the MVC HTML page using data-ng-repeat.
- // This method is to get all the kids Learn Details to display for CRUD.
- select KidsLearnDetails($scope.sImage);
- function selectKidsLearnDetails(IMAGENAME) {
- $http.get('/api/KidsLearnAPI/getKIDSLEARNSelectALL/', { params: { IMAGENAME: IMAGENAME } }).success(function (data) {
- $scope.KidsLearnData = data;
- $scope.showKidsAdd = true;
- $scope.addEditKids = false;
- $scope.KidsList = true;
- $scope.showItem = true;
- if ($scope.KidsLearnData.length > 0) {
- }
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
- //Search
- $scope.searchKidsLearnDetails = function () {
- selectKidsLearnDetails($scope.sImage);
- }
Search Button Click
- <table style="color:#9F000F;font-size:large" cellpadding="4" cellspacing="6">
- <tr>
- <td>
- <b>Image Name</b>
- </td>
- <td>
- : <input type="text" name="txtMenuID" ng-model="sImage" value="" />
- <br />
- </td>
- <td>
- <input type="submit" value="Search" style="background-color:#336699;color:#FFFFFF" ng-click="searchKidsLearnDetails()" />
- </td>
- </tr>
- </table>

Insert new Question
In the ADD/Edit Details
button click we will make visible the Question. Add table details where the Admin
user can enter the new Question information. For a new Menu we will make the
Menu ID as 0. In the New Menu save button click we will call the save
method.
- // New Kids Details Add Details
- $scope.showKidsAddDetails = function () {
- cleardetails();
- $scope.showKidsAdd = true;
- $scope.addEditKids = true;
- $scope.KidsList = true;
- $scope.showItem = true;
- }
In the Save method we will check for the kidsIdentity. If the kidsIdentitys is “0” then it will insert the new question Master. Here we will call the Insert Web API method and if the MenuIdentitys is > 0 then it means to update the Menu record then we will call the Update Web API method.
Image Upload: In Edit and Add new question admin can upload image to our root folder and image name will be saved to our database.
$scope.ChechFileValid
This method
checks if the attached image file is valid or not. If the image file is not valid
then display the error message.
$scope.SaveDetail = function ()
In this method pass the image file to the UploadFile method and once the image
is uploaded successfully to our root folder the item details will be inserted
into database.
fac.UploadFile = function (file) In this method using $http.post we pass our image file to the MVC Controller and our HTTP Post method as in the following:
- //Declarationa and Function for Image Upload and Save Data
- //--------------------------------------------
- // Variables
- $scope.Message = "";
- $scope.FileInvalidMessage = "";
- $scope.SelectedFileForUpload = null;
- $scope.FileDescription_TR = "";
- $scope.IsFormSubmitted = false;
- $scope.IsFileValid = false;
- $scope.IsFormValid = false;
- //Form Validation
- $scope.$watch("f1.$valid", function (isValid) {
- $scope.IsFormValid = isValid;
- });
- // THIS IS REQUIRED AS File Control is not supported 2 way binding features of Angular
- // ------------------------------------------------------------------------------------
- //File Validation
- $scope.ChechFileValid = function (file) {
- var isValid = false;
- if ($scope.SelectedFileForUpload != null) {
- if ((file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') && file.size <= (800 * 800)) {
- $scope.FileInvalidMessage = "";
- isValid = true;
- }
- else {
- $scope.FileInvalidMessage = "Only JPEG/PNG/Gif Image can be upload )";
- }
- }
- else {
- $scope.FileInvalidMessage = "Image required!";
- }
- $scope.IsFileValid = isValid;
- };
- //File Select event
- $scope.selectFileforUpload = function (file) {
- var files = file[0];
- $scope.Imagename = files.name;
- // alert($scope.Imagename);
- $scope.SelectedFileForUpload = file[0];
- }
- //----------------------------------------------------------------------------------------
- //Save File
- $scope.saveDetails = function () {
- $scope.IsFormSubmitted = true;
- $scope.Message = "";
- $scope.ChechFileValid($scope.SelectedFileForUpload);
- if ($scope.IsFormValid && $scope.IsFileValid) {
- FileUploadService.UploadFile($scope.SelectedFileForUpload).then(function (d) {
- //if the MenuIdentity ID=0 means its new Menu insert here i will call the Web api insert method
- if ($scope.kidsIdentitys == 0) {
- $http.get('/api/KidsLearnAPI/insertKIDSLEARN/', { params: { IMAGENAME: $scope.Imagename, ANSWER: $scope.Answer, HINTQUESTION: $scope.Question } }).success(function (data) {
- $scope.menuInserted = data;
- alert($scope.menuInserted);
- cleardetails();
- selectKidsLearnDetails('');
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
- else { // to update to the Menu details
- $http.get('/api/KidsLearnAPI/updateKIDSLEARN/', { params: { kidsIdentity: $scope.kidsIdentitys, IMAGENAME: $scope.Imagename, ANSWER: $scope.Answer, HINTQUESTION: $scope.Question } }).success(function (data) {
- $scope.menuUpdated = data;
- alert($scope.menuUpdated);
- cleardetails();
- selectKidsLearnDetails('');
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
- }, function (e) {
- alert(e);
- });
- }
- else {
- $scope.Message = "All the fields are required.";
- }
- };
- })
- .factory('FileUploadService', function ($http, $q) {
- var fac = {};
- fac.UploadFile = function (file) {
- var formData = new FormData();
- formData.append("file", file);
- var defer = $q.defer();
- $http.post("/KidslearnAdmin/UploadFile", formData,
- {
- withCredentials: true,
- headers: { 'Content-Type': #ff0000 },
- transformRequest: angular.identity
- })
- .success(function (d) {
- defer.resolve(d);
- })
- .error(function () {
- defer.reject("File Upload Failed!");
- });
- return defer.promise;
- }
- return fac;
- //---------------------------------------------
- //End of Image Upload and Insert record
Add MVC controller for Admin page:
We will create new MVC controller named as KidsLearnAdminContrller. In this controller first we check if the user role is admin and also an authorized user. If the user is not logged in and not a Admin user then we will redirect to login page. If the user is logged in then we display the Admin Question Management page.
- // GET: KidslearnAdmin
- public string RoleName { get; set; }
- // GET: Users
- public Boolean isAdminUser()
- {
- if (User.Identity.IsAuthenticated)
- {
- var user = User.Identity;
- ApplicationDbContext context = new ApplicationDbContext();
- var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
- var s = UserManager.GetRoles(user.GetUserId());
- RoleName = s[0].ToString();
- if (RoleName == "Admin")
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- return false;
- }
- // GET: Menu
- public ActionResult Index()
- {
- if (User.Identity.IsAuthenticated)
- {
- var user = User.Identity;
- ViewBag.Name = user.Name;
- // ApplicationDbContext context = new ApplicationDbContext();
- // var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
- //var s= UserManager.GetRoles(user.GetUserId());
- ViewBag.displayMenu = "No";
- if (isAdminUser())
- {
- ViewBag.UserRole = RoleName;
- ViewBag.displayMenu = "YES";
- return View();
- }
- else
- {
- return RedirectToAction("Index", "Home");
- }
- }
- else
- {
- return RedirectToAction("Index", "Home");
- ViewBag.Name = "Not Logged IN";
- }
- return RedirectToAction("Index", "Home");
- }
In this controller we use the UploadFile method to upload the image to our root folder.
Note:
$http.post(“”) we need to provide our MVC Controller name and
our HTTPost method name, where we upload the image to our root folder. The following
is the code to upload an image to our MVC Controller.
- [HttpPost]
- public JsonResult UploadFile()
- {
- string Message, fileName;
- Message = fileName = string.Empty;
- bool flag = false;
- if (Request.Files != null)
- {
- var file = Request.Files[0];
- fileName = file.FileName;
- try
- {
- file.SaveAs(Path.Combine(Server.MapPath("~/Images"), fileName));
- Message = "File uploaded";
- flag = true;
- }
- catch (Exception)
- {
- Message = "File upload failed! Please try again";
- }
- }
- return new JsonResult { Data = new { Message = Message, Status = flag } };
- }

Same as with admin we will add new AngularJS Controller and we give the AngularJS controller name as KidsController for user module and we declare all local variables to be used.
- /// <reference path="../angular.js" />
- /// <reference path="../angular.min.js" />
- /// <reference path="../angular-animate.js" />
- /// <reference path="../angular-animate.min.js" />
- var app;
- (function () {
- app = angular.module("AngularJs_ImageModule", ['ngAnimate']);
- })();
- app.controller("AngularJs_ImageController", function ($scope, $timeout, $rootScope, $window, $http) {
- //Global Variables
- $scope.date = new Date();
- $scope.MyName = "Shanu";
- $scope.usrName = "";
- $scope.Images;
- $scope.txtAnswer = "";
- //Game variable declared
- //This variable has been declared to display the Question Number,User Total Points on each questions,
- //Each question Answer Correct Word total character Count for example from the Images display the correct answer is Fire then i will display 4 as total Word Count.
- //rowCount is used to display the Question one by one.
- $scope.questionCount = 1;
- $scope.answerCount = 1;
- $scope.totalPoints = 0
- $scope.wordCount = 0;
- $scope.rowCount = 0;
- //Game Detail Display Variables
- $scope.Image1 = "";
- $scope.ImageAnswer = "won.png";
- $scope.Answers = "";
- $scope.HintQuestion = "";
- $scope.Resuts = "";
- // --
- //Game Hidden Table row display
- $scope.showGameStart = true;
- $scope.showGame = false;
- $scope.showresult = false;
- //Sound file for play sounds
- $scope.mp3 = "~/Sounds/Key.wav"
By default we will display how to play the game and the rules to play the game and the instructions to start the game. The user can enter their name to start the game. The user cannot start the game without entering their name.
In the Start game button click I call the AngularJS method startGame to check whether the user has entered their name. If the user has not entered their name I will ask to enter the name to start the game. If the user has entered their name then I will call the function to display the first question for the user.
- $scope.startGame = function () {
- $scope.playKeySound();
- if ($scope.usrName == '') {
- alert("Enter Your Name to start the game !");
- $scope.showGameStart = true;
- $scope.showGame = false;
- $scope.showresult = false;
- }
- else {
- $scope.questionCount = 1;
- $scope.totalPoints = 0;
- $scope.wordCount = 0;
- $scope.rowCount = 0;
- $scope.answerCount = 1;
- selectGameDetails('');
- $scope.showGameStart = false;
- $scope.showGame = true;
- $scope.showresult = false;
- }
- }
Play Sound:
Here I have used Windows default sound for each button click and for correct and wrong answers. In our MVC page we add HTML5 Audio Element tag for playing the sounds.
- <tr ng-show="showSounds">
- <td>
- <audio id="audio1" >
- <source src="@Url.Content("~/Sounds/Key.wav")"></source>
- Your browser isn't invited for super fun audio time.
- </audio>
- <audio id="audioOK">
- <source src="@Url.Content("~/Sounds/Alarm07Ok.wav")"></source>
- Your browser isn't invited for super fun audio time.
- </audio>
- <audio id="audioNG">
- <source src="@Url.Content("~/Sounds/Alarm06NOK.wav")"></source>
- Your browser isn't invited for super fun audio time.
- </audio>
- </td>
- </tr>
- $scope.playKeySound = function () {
- var audio2 = document.getElementById("audio1");
- audio2.volume = 1;
- audio2.play();
- }
- $scope.playOKSound = function () {
- var audio2 = document.getElementById("audioOK");
- audio2.volume = 1;
- audio2.play();
- }
- $scope.playNOKSound = function () {
- var audio2 = document.getElementById("audioNG");
- audio2.volume = 1;
- audio2.play();
- }

When the user clicks on the Start game button we display questions number 1, the total points as 0 and using the $http.get('/api/KidsLearnAPI/getKIDSLEARNSelect/', { params: { IMAGENAME: IMAGENAME } }) we will get 10 random questions from the database and will store the result data to $scope.Images. For the first question the rowcount will be 0, I will display the first question's information with a Hint Answer.
- //get all image Details
- function selectGameDetails(IMAGENAME) {
- $http.get('/api/KidsLearnAPI/getKIDSLEARNSelect/', { params: { IMAGENAME: IMAGENAME } }).success(function (data) {
- $scope.Images = data;
- if ($scope.Images.length > 0) {
- $scope.Image1 = $scope.Images[$scope.rowCount].IMAGENAME;
- $scope.Answers = $scope.Images[$scope.rowCount].ANSWER;
- $scope.HintQuestion = $scope.Images[$scope.rowCount].HINTQUESTION;
- $scope.wordCount = $scope.Answers.length;
- }
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
Next Question button Click
In the next button we will check for each answer result entered by the user.
Correct
Answer:
We will check the user entered answer with
the database result answer. If both answers are correct then we will display
the result to answer and award the user 20 total points.

We will check the user-entered answer with the database result answer. If both answers are incorrect then we will display the result to answer and deduct the user total points by 10 (-10).

Final Result, the User Won/Lose the Game
When the user
has answered all the 10 questions we will check for the result of Total Points
for the user and if the points are less than 200 then we will display the
message to the user that they have lost the game.
Here is the AngularJS code to check the user result and display the message.
- // to find the Answer
- $scope.findAnswer = function () {
- if ($scope.txtAnswer == "") {
- alert("Enter the Answer");
- return;
- }
- if ($scope.txtAnswer.toLowerCase() == $scope.Answers.toLowerCase()) {
- $scope.playOKSound();
- alert("Wow :) You have enter the correct answer and you have got 20 Points for this Answer")
- if ($scope.answerCount <= 9) {
- $scope.answerCount = $scope.answerCount + 1;
- }
- $scope.totalPoints = $scope.totalPoints + 20;
- }
- else {
- $scope.playNOKSound();
- if ($scope.answerCount > 1)
- {
- $scope.answerCount = $scope.answerCount - 1;
- }
- alert("Sorry :( You have enter the wrong answer and you have got -10 points")
- $scope.totalPoints = $scope.totalPoints - 10;
- }
- $scope.txtAnswer = "";
- if ($scope.questionCount == 10) {
- if ($scope.totalPoints >= 200) {
- $scope.playOKSound();
- $scope.Resuts = "Wow :) You have won the Game.Good Job " + $scope.usrName;
- alert($scope.Resuts)
- $scope.ImageAnswer = "won.png";
- }
- else {
- $scope.Resuts = "Sorry " + $scope.usrName + " You lose the game :( .Your Total points are " + $scope.totalPoints + " out of 100 points"
- alert($scope.Resuts);
- $scope.ImageAnswer = "lose.png";
- }
- $scope.showGameStart = false;
- $scope.showGame = false;
- $scope.showresult = true;
- return;
- }
- else {
- $scope.questionCount = $scope.questionCount + 1;
- $scope.wordCount = 0;
- $scope.rowCount = $scope.rowCount + 1;
- $scope.Image1 = $scope.Images[$scope.rowCount].image1;
- $scope.Image1 = $scope.Images[$scope.rowCount].IMAGENAME;
- $scope.Answers = $scope.Images[$scope.rowCount].ANSWER;
- $scope.HintQuestion = $scope.Images[$scope.rowCount].HINTQUESTION;
- $scope.wordCount = $scope.Answers.length;
- }
- }
Conclusion
Firstly, create a sample KidsLearnerDB Database in your SQL Server. In the Web.Config file change the DefaultConnection connection string with your SQL Server Connections. You can find default connection string and one more as Entity connection string change both as per your SQL connection.


Thiruppathi RPosted Jun 16, 2016, 8:19 AM
Great article..
Shakti Singh DulawatPosted Apr 25, 2016, 10:22 AM
Wonderful and very helping for new Angular developer keep it up man
Rahul Kumar SaxenaPosted Apr 17, 2016, 7:57 AM
Congrats Syed Shanu... Article Of the day
Gowtham RajamanickamPosted Apr 2, 2016, 12:40 PM
Good one..
Upendra Pratap ShahiPosted Mar 3, 2016, 9:38 AM
nice explain sir...thanks for sharing such a great article...
Sibeesh VenuPosted Mar 3, 2016, 7:49 AM
Syed Shanu Sure. Welcome
Sibeesh VenuPosted Mar 3, 2016, 6:34 AM
There is a typo error in User Module "where this application's aim is for kidsto ". Please change it to "where this application's aim is for kids to ". And also in reference part "OWIN andKatana" to "OWIN and Katana". In the Angular JS select method "select KidsLearnDetails($scope.sImage); " to "selectKidsLearnDetails($scope.sImage);"
Thennarasu NPosted Mar 3, 2016, 2:20 AM
GREAT SIR
Asfend YarPosted Mar 3, 2016, 2:13 AM
nice
Shubham KumarPosted Mar 3, 2016, 12:14 AM
nice
Syed ShanuPosted Mar 2, 2016, 7:31 PM
Thank You All
sreenivasa kPosted Mar 2, 2016, 5:50 PM
nice one
Sibeesh VenuPosted Mar 2, 2016, 8:23 AM
That was a great read :)
Vignesh ManiPosted Mar 2, 2016, 6:46 AM
Nice Share
Mohammed IbrahimPosted Mar 2, 2016, 2:54 AM
nice
Jaipal ReddyPosted Mar 1, 2016, 11:21 PM
Thank you sir. .
Humayun Kabir MamunPosted Mar 1, 2016, 11:06 PM
Nice...
Syed ShanuPosted Mar 1, 2016, 11:03 PM
Thank You all for your comments
Debasis SahaPosted Mar 1, 2016, 1:39 PM
good one..
Ammar ShaukatPosted Mar 1, 2016, 12:33 PM
You did a great job . wrote a long article . well that's nice.
Kumaresh RajalingamPosted Mar 1, 2016, 12:31 PM
Good one
Asfend YarPosted Mar 1, 2016, 11:57 AM
nice
Ankur MistryPosted Mar 1, 2016, 7:45 AM
Very nice Brother, thanks for sharing
Ganjo AliPosted Mar 1, 2016, 6:44 AM
good
Anupam SinghPosted Mar 1, 2016, 5:06 AM
cool stuff. nice share
Ehsan SajjadPosted Mar 1, 2016, 4:31 AM
Very good work.