使用 MVC 和 AngularJS 的 Easy Kids Learn






4.83/5 (15投票s)
在本文中,您将学习如何使用 MVC 和 AngularJS 创建 Kids Learn 游戏。
引言
请观看我的 YouTube 视频链接,了解 我如何使用 MVC 让孩子轻松学习。
什么是 EASY KIDS LEARN?
这是一个儿童轻松学习游戏。在这里,我们显示 10 个问题,每个问题中,我们会显示一张图片,并为每个问题显示提示。孩子们需要输入每张图片所代表的正确拼写。例如,我们显示图片 10,孩子们需要输入正确的单词拼写“TEN”。所有图片、提示问题和答案都将由管理员发布。管理员可以随时为用户(这里是孩子们)添加任意数量带有提示问题和答案的图片,每次都会随机显示 10 个问题。使用此应用程序,孩子们可以轻松学习单词的拼写。
此应用程序有两个模块
- 管理员模块
- 用户模块
管理员模块
用户模块
在本文中,我们将了解如何使用 ASP.NET MVC、WEB API 和 AngularJS 创建和管理问题,供管理员和用户玩游戏。
在这里,我们将看到:
- 轻松儿童问题管理(只有管理员用户可以查看所有/创建/删除和编辑问题)。
- 用户如何通过输入姓名从主页玩游戏。
必备组件
Visual Studio 2015:您可以从 此处 下载。
使用代码
1. 创建数据库和表
我们将在“KidsLearnerDB”数据库下创建一个 KidsLearnerMaster 表。以下是创建数据库、表和示例插入查询的脚本。在您的 SQL Server 中运行此脚本。我使用的是 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')
所有这 10 个默认图片都已上传到我的根文件夹 /Images。您可以使用应用程序直接添加更多问题和图片。
存储过程:逐一在您的 SQL Server 中运行所有这些过程。用于选择所有记录以供管理员显示的 SP。
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
用于选择前 10 个随机记录以供用户玩游戏的 SP。
-- 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
GO
管理员用于插入记录的 SP
-- 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
管理员用于更新记录的 SP
-- 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
管理员用于删除记录的 SP
-- 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
在 Visual Studio 2015 中创建您的 MVC Web 应用程序
安装 Visual Studio 2015 后,单击开始,然后单击程序,选择 Visual Studio 2015 - 单击 Visual Studio 2015。单击新建,然后单击项目,选择 Web,然后选择 ASP.NET Web 应用程序。输入您的项目名称,然后单击确定。
选择 MVC、WEB API,然后单击确定。
Web.Config
在 web.config 文件中,我们可以找到 DefaultConnection 连接字符串。默认情况下,ASP.NET MVC 将使用此连接字符串来创建所有 ASP.NET Identity 相关的表,如 AspNetUsers 等。对于我们的应用程序,我们还需要使用该数据库来处理其他页面活动,而不是使用两个不同的数据库,一个用于用户详细信息,一个用于我们自己的功能。在这里,我将使用一个数据库,其中将创建所有 ASP.NET Identity 表,并且我们还可以为其他页面用途创建自己的表。
在此连接字符串中,更改您的 SQL Server 名称、UID 和 PWD,以在单个数据库中创建和存储所有用户详细信息。
<connectionStrings>
<add name="DefaultConnection" connectionString="data source=YOURSERVERNAME;initial catalog= KidsLearnerDB;user id=UID;password=PWD;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
为管理员用户创建默认角色
首先,创建默认用户角色,例如“Admin”,我们还将创建一个默认管理员用户。我们将在“Startup.cs”中创建所有默认角色和用户。
OWIN(.NET 的开放 Web 接口)定义了 .NET 和 WEB 服务器之间的标准接口,每个 OWIN 应用程序都有一个 Startup Class,我们可以在其中指定组件。
参考
在“Startup.cs”文件中,我们可以找到 Configuration 方法。从此方法中,我们将调用我们的 createRolesandUsers() 方法来创建默认用户角色和用户。我们将检查角色是否已创建。如果角色(如 Admin)未创建,那么我们将创建一个名为“Admin”的新角色,然后创建一个默认用户并将用户角色设置为 Admin。我们将使用此用户作为超级用户,该用户可以从我们的 MVC 应用程序中管理问题。
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 = "syedshanumcain@gmail.com";
user.Email = "syedshanumcain@gmail.com";
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");
}
}
}
当我们运行我们的应用程序时,我们可以在 KidsLearnerDB 数据库中看到新创建的默认 ASP.NET 用户相关表。
使用 ADO.NET 实体数据模型添加数据库
右键单击我们的项目,然后单击添加,然后单击新项目。选择数据,然后选择ADO.NET Entity Data Model,并为我们的 EF 命名,然后单击,
选择“EF Designer from database”并单击下一步。
连接到我们的数据库。单击下一步以选择我们的表和用于菜单管理的存储过程。
在这里,我们可以看到新创建的 KidsLearnerMaster 表以及现有的 ASP.NET Identity 表,并且已选择所有新创建的存储过程来执行我们的 KidsLearnerMaster CRUD 操作。
单击完成。
添加 Web API 控制器的过程
右键单击 Controllers 文件夹,单击添加,然后单击 Controller。
选择 Web API 2 Controller – Empty,单击添加,然后为我们的 WEB API 控制器命名。
使用 WEBAPI 控制器进行 CRUD 操作
选择 Controller 并添加一个空的 Web API 2 Controller。为您的 Web API 控制器提供名称,然后单击 OK。在这里,我为我的 Web API Controller 命名为“KIDSLEARNAPIController”。由于我们创建了 Web API Controller,我们可以看到我们的 Controller 已继承了 ApiController。正如我们所知,Web API 是构建浏览器和移动设备 HTTP 服务的简单易行的方法。
Web API 具有以下四种方法:Get/Post/Put 和 Delete,其中
- Get 用于请求数据。(Select)
- Post 用于创建数据。(Insert)
- Put 用于更新数据。
- Delete 用于删除数据。
Get 方法
在我们的示例中,由于我只使用了一个存储过程,所以我只使用了 Get 方法。我们需要创建一个 Entity 对象并编写 Get 方法来执行 Select/Insert/Update 和 Delete 操作。
查询操作
我们使用 get 方法通过 Entity 对象获取 KidslearnMasters 表的所有详细信息,并将结果作为 IEnumerable 返回。我们在 AngularJS 中使用此方法,并在 AngularJS 控制器中将结果显示在 MVC 页面上。使用 Ng-Repeat,我们可以绑定详细信息。
在这里,我们可以看到在 getKIDSLEARNSelect 方法中,我将搜索参数传递给了 USP_KIDSLEARN_Select ALL 存储过程。在存储过程中,如果搜索参数为空,我使用“%”返回所有记录。
// 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();
}
接下来,我们还有一个 Select 方法。此方法将用于向用户显示前 10 个随机问题。
// 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();
}
插入操作与 select 相同,我们将所有参数传递给 insert 过程。此 insert 方法将返回数据库的结果,表示记录是否已插入。我们将获取结果并从 AngularJS Controller 显示到 MVC 应用程序。
// To insertKIDSLEARN
[HttpGet]
public IEnumerable<string> insertKIDSLEARN(string IMAGENAME, string ANSWER, string HINTQUESTION)
{
return objapi.USP_KIDSLEARN_Insert(IMAGENAME, ANSWER, HINTQUESTION).AsEnumerable();
}
更新操作
与 insert 相同,我们将所有参数传递给 Update 过程。此 Update 方法将返回数据库的结果,表示记录是否已更新。
//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();
}
删除操作
与 insert 相同,我们将所有参数传递给 Delete 过程。此 Delete 方法将返回数据库的结果,表示记录是否已删除。
//to Update deleteKIDSLEARN
[HttpGet]
public string deleteKIDSLEARN(string kidsIdentity)
{
objapi.USP_KIDSLEARN_Delete(kidsIdentity);
objapi.SaveChanges();
return "deleted";
}
管理员模块
在管理员模块中,管理员可以登录并管理所有儿童问题详细信息。
创建 AngularJS 控制器
首先,在 Scripts 文件夹中创建一个文件夹,我们将文件夹命名为“MyAngular”。
现在将您的 Angular Controller 添加到该文件夹中。
右键单击 MyAngular 文件夹,单击添加,然后单击新项目。选择 Web,然后选择 AngularJS Controller,并为 Controller 提供一个名称。我将我的 AngularJS Controller 命名为“Controller.js”。
创建 AngularJS Controller 后,我们可以看到默认情况下 Controller 将包含带有默认模块定义的代码等。
如果缺少 AngularJS 包,则将包添加到您的项目中。右键单击您的 MVC 项目,然后单击管理 NuGet 程序包。搜索 AngularJS,然后单击安装。
创建菜单 CRUD 的 AngularJS 脚本文件的过程
Modules.js:在这里,我们将添加对 AngularJS JavaScript 的引用,并创建一个名为“AngularJs_Module”的 Angular 模块。
// <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:在 AngularJS Controller 中,我完成了所有业务逻辑,并将数据从 Web API 返回到我们的 MVC HTML 页面。
变量声明:首先,我们声明了所有需要使用的局部变量。
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 = "";
方法
Select 方法 在 select 方法中,我使用了 $http.get 从 Web API 获取详细信息。在 get 方法中,我将提供我们的 API Controller 名称和方法来获取详细信息。
最终结果将使用 data-ng-repeat 显示在 MVC HTML 页面上。
// This method is to get all the kids Learn Details to display for CRUD.
selectKidsLearnDetails($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);
}
插入新问题
在“添加/编辑详细信息”按钮点击时,我们将使问题可见。添加表详细信息,管理员用户可以在其中输入新问题信息。对于新菜单,我们将菜单 ID 设置为 0。在“新菜单保存”按钮点击时,我们将调用 save 方法。
// New Kids Details Add Details
$scope.showKidsAddDetails = function () {
cleardetails();
$scope.showKidsAdd = true;
$scope.addEditKids = true;
$scope.KidsList = true;
$scope.showItem = true;
}
在 Save 方法中,我们将检查 kidsIdentity。如果 kidsIdentity 为“0”,则插入新的问题 Master。在这里,我们将调用 Insert Web API 方法;如果 MenuIdentity 大于 0,则表示更新 Menu 记录,然后我们将调用 Update Web API 方法。
图片上传:在编辑和添加新问题时,管理员可以将图片上传到我们的根文件夹,图片名称将保存到我们的数据库。
$scope.ChechFileValid
此方法检查附加的图片文件是否有效。如果图片文件无效,则显示错误消息。
$scope.SaveDetail = function ()
在此方法中,我们将图片文件传递给 UploadFile 方法,一旦图片成功上传到我们的根文件夹,项目详细信息将插入到数据库中。
fac.UploadFile = function (file) 在此方法中使用 $http.post,我们将图片文件传递给 MVC Controller,并使用以下 HTTP Post 方法:
//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': undefined }, 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
为管理员页面添加 MVC 控制器
我们将创建名为 KidsLearnAdminContrller 的新 MVC 控制器。在此控制器中,我们首先检查用户角色是否为管理员,并且也是授权用户。如果用户未登录且不是管理员用户,我们将重定向到登录页面。如果用户已登录,我们将显示管理员问题管理页面。
// 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");
}
在此控制器中,我们使用 UploadFile 方法将图片上传到我们的根文件夹。
注意:$http.post(“”),我们需要提供我们的 MVC Controller 名称和我们的 HTTPost 方法名称,其中我们将图片上传到我们的根文件夹。以下是将图片上传到我们的 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 } };
}
用户模块
与管理员相同,我们将添加新的 AngularJS Controller,并将 AngularJS Controller 命名为 KidsController 以供用户模块使用,并声明所有将要使用的局部变量。
/// <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"
游戏开始函数
默认情况下,我们将显示如何玩游戏,游戏的规则以及开始游戏的说明。用户可以通过输入姓名来开始游戏。用户未输入姓名则无法开始游戏。
在“开始游戏”按钮点击时,我调用 AngularJS 方法 startGame 来检查用户是否已输入姓名。如果用户未输入姓名,我将要求他们输入姓名才能开始游戏。如果用户已输入姓名,则我将调用函数向用户显示第一个问题。
$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;
}
}
播放声音
在这里,我使用了 Windows 默认声音进行每次按钮点击,以及正确和错误的答案。在我们的 MVC 页面中,我们添加了 HTML5 Audio Element 标签来播放声音。
<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>
在我们的 AngularJS Controller 中,在每次按钮点击、正确答案和错误答案时,我们都会调用相应的方法来播放声音。
$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();
}
selectGameDetails() 显示每个问题。
当用户点击“开始游戏”按钮时,我们将显示问题编号 1,总分 0,并通过 $http.get('/api/KidsLearnAPI/getKIDSLEARNSelect/', { params: { IMAGENAME: IMAGENAME } })
从数据库获取 10 个随机问题,并将结果数据存储到 $scope.Images。对于第一个问题,行计数为 0,我将显示第一个问题的信息以及提示答案。
//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!";
});
}
下一个问题按钮点击
在下一个按钮中,我们将检查用户输入的每个答案结果。
正确答案
我们将用户的输入答案与数据库结果答案进行比较。如果两个答案都正确,我们将向用户显示结果,并奖励用户 20 分。
错误答案
我们将用户的输入答案与数据库结果答案进行比较。如果两个答案都不正确,我们将向用户显示结果,并扣除用户总分 10 分(-10 分)。
最终结果,用户赢/输了游戏
当用户回答完所有 10 个问题后,我们将检查用户的总分结果,如果分数低于 200,我们将向用户显示他们输了游戏的消息。
这是检查用户结果并显示消息的 AngularJS 代码。
// 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;
}
}
关注点
首先,在您的 SQL Server 中创建一个名为 KidsLearnerDB 的示例数据库。在 Web.Config 文件中更改 DefaultConnection 连接字符串以使用您的 SQL Server 连接。在 Startup.cs 文件中,我创建了默认的管理员用户,用户名为“shanu”,密码为“A@Z200711”。此用户名和密码将用于登录管理员用户。您可以根据需要更改此用户名和密码。出于安全原因,作为管理员登录后,您可以自行更改管理员用户的密码。
历史
shanuEasyKidsLearnerMVCAngularJS.zip - 2016/03/02