[Web API series] 1.3-practice: use ASP. NET Web API and Angular. js to create a single page application (below)

Source: Internet
Author: User

[Web API series] 1.3-practice: use ASP. NET Web API and Angular. js to create a single page application (below)
Exercise 2: Create a SPA Interface

In this exercise, you will first create a web front-end for Geek Quiz and use AngularJS to focus on the interaction of single-page applications. Then you will use CSS3 to execute a variety of animations and provide a visual effect of switching context when switching from one question to another to enhance the user experience.

Task 1: Use AngularJS to create the SPA Interface

In this task, you will use AngularJS to implement the client of the Geek Quiz application. AngularJS is an open-source JavaScript framework that can be used with MVC to enhance browser-based applications, making development and testing more convenient.

You will start from installing AngularJS on the Package Manager Console of Visual Studio. Then, you will create a controller that provides Geek Quiz app behavior and a view that uses AngularJS template engine to submit quiz questions and answers.

Note: For more information about AngularJS, see http://angularjs.org /.
1. Open Visual Studio Express 2013 for Web and open the GeekQuiz. sln solution located under the Source/Ext2-CreatingASPAInterface/Begin folder. Alternatively, you can continue with the solution reserved for the previous exercise.
2. Open the Package Manager Console under Tools | Library Package Manager, and type the following command to install the NuGet Package of AngularJS. Core.
Install-Package AngularJS. Core
3. In Solution Explorer, right-click the Scripts Folder under the GeekQuiz project and select Add | New Folder. Name the folder app and press Enter.
4. Right-click the app folder you just created and select Add | JavaScript File.

In the Specify Name for Item dialog box, type quiz-controller in the Iten name text box and click OK.

In the quiz-controller.js file, add the following code to declare and initialize AngularJS's QuizCtrl controller.
angular.module('QuizApp', [])    .controller('QuizCtrl', function ($scope, $http) {        $scope.answered = false;        $scope.title = "loading question...";        $scope.options = [];        $scope.correctAnswer = false;        $scope.working = false;        $scope.answer = function () {            return $scope.correctAnswer ? 'correct' : 'incorrect';        };    });

Note: The expected parameter of the QuizCtrl constructor is named Scope. The initial status of the scope should be set in the constructor. Scope object. This attribute contains the view model and can access the template when the controller is registered.

The QuizCtrl controller is defined in a module named QuizApp. A module is a unit of work that allows you to divide an application into independent components. The main advantage of the use module is that the Code is easier to understand, easier to unit test, reusable, and maintainable.
7. Now you will add actions to the scope to respond to event triggers from the view. Add the following code to the bottom of the QuizCtrl controller, which defines the nextQuestion function in the $ scope object.

.controller('QuizCtrl', function ($scope, $http) {     ...    $scope.nextQuestion = function () {        $scope.working = true;        $scope.answered = false;        $scope.title = "loading question...";        $scope.options = [];        $http.get("/api/trivia").success(function (data, status, headers, config) {            $scope.options = data.options;            $scope.title = data.title;            $scope.answered = false;            $scope.working = false;        }).error(function (data, status, headers, config) {            $scope.title = "Oops... something went wrong";            $scope.working = false;        });    };};

Note: This function extracts the next question from the Web API Trivia created in the previous exercise and attaches the question data Scope object. 8. Add the following code to the bottom of the QuizCtrl controller. The sendAnswer function is defined in the scope object.

.controller('QuizCtrl', function ($scope, $http) {     ...    $scope.sendAnswer = function (option) {        $scope.working = true;        $scope.answered = true;        $http.post('/api/trivia', { 'questionId': option.questionId, 'optionId': option.id }).success(function (data, status, headers, config) {            $scope.correctAnswer = (data === true);            $scope.working = false;        }).error(function (data, status, headers, config) {            $scope.title = "Oops... something went wrong";            $scope.working = false;        });    };};

Note: This function sends the result to Trivia Web API Based on the selected answer and stores the result-for example, whether the result is correct-to the $ scope object.

The next step is to create an AngularJS template to define the quiz view. Open the Index. cshtml file in the Views | Home folder and replace the file with the following code:
@{    ViewBag.Title = "Play";}

{{answer()}}

Next Question

{{title}}

{{option.title}}@section scripts { @Scripts.Render("~/Scripts/angular.js") @Scripts.Render("~/Scripts/app/quiz-controller.js") }

Note: AngularJS templates are declarative specifications. You can use the model and controller information to convert static tags to dynamic views in a visible browser. The following is an example of AngularJS elements and element attributes used in the template:
1. the ng-app Command tells AngularJS to indicate the DOM element of the application root element.
2. the ng-controller command adds the controller to the DOM at the position declared by the command.
3. The curly braces {} indicate the attributes bound to the scope defined in the controller.
4. the ng-click command is used to respond to user clicks and execute functions defined in scope.

Open the site.css file under the contentfile folder and add the following highlighted style to the bottom of the file. It provides a good quiz view.
.validation-summary-valid {     display: none;}/* Geek Quiz styles */.flip-container .back,.flip-container .front {     border: 5px solid #00bcf2;     padding-bottom: 30px;     padding-top: 30px;}#content {    position:relative;    background:#fff;    padding:50px 0 0 0;}.option {     width:140px;     margin: 5px;}div.correct p {     color: green;}div.incorrect p {     color: red;}.btn {     border-radius: 0;}.flip-container div.front, .flip-container div.back.flip {    display: block;}.flip-container div.front.flip, .flip-container div.back {    display: none;}

Task 2: Running Solution

In this task, you will execute the new user interface you created with AngularJS to answer some quiz questions.

1. Press F5 to run the solution
2. register a new account. Redo the registration step of Task 3 in Exercise 1.
Note: If you are using the solution retained in the previous exercise, you can use the previously registered account.
3. The Home page displays the first quiz problem. Click an option to answer the question. This triggers the previously defined sendAnswer function, which sends the selected option to Trivia Web API.

4. Click one of the buttons and the result is displayed. Click Next Question to display the following questions. This triggers the nextQuestion function defined in the controller.

5. The next problem may occur. Answer as many questions as possible. After completing all the questions, you should return the first question.

6. Return to Visual Studio and press Shift + F5 to stop debugging.
Task 3: Use CSS3 to create a flip Animation <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Export/z8K1xENvbnRlbnTOxLz + vNCjrLKi0aHU8UFkZCA = "Existing Item.

2. In the Add Existing Item dialog box, navigate to the Source/assets folder and select flip.css. Click OK.

3. Open flip.css and check its content.
4. Jump to the flip transformation annotation. The following styles use the perspective and rotateY transformations of CSS to generate a "card flip" effect.

/* flip transformation */.flip-container div.front { -moz-transform: perspective(2000px) rotateY(0deg); -webkit-transform: perspective(2000px) rotateY(0deg); -o-transform: perspective(2000px) rotateY(0deg); transform: perspective(2000px) rotateY(0deg);} .flip-container div.front.flip { -moz-transform: perspective(2000px) rotateY(179.9deg); -webkit-transform: perspective(2000px) rotateY(179.9deg); -o-transform: perspective(2000px) rotateY(179.9deg); transform: perspective(2000px) rotateY(179.9deg); }.flip-container div.back { -moz-transform: perspective(2000px) rotateY(-180deg); -webkit-transform: perspective(2000px) rotateY(-180deg); -o-transform: perspective(2000px) rotateY(-180deg); transform: perspective(2000px) rotateY(-180deg);} .flip-container div.back.flip { -moz-transform: perspective(2000px) rotateY(0deg); -webkit-transform: perspective(2000px) rotateY(0deg); -ms-transform: perspective(2000px) rotateY(0); -o-transform: perspective(2000px) rotateY(0); transform: perspective(2000px) rotateY(0); }

5. Jump to the hide back of pane during flip comment.

/* hide back of pane during flip */.front, .back { -moz-backface-visibility: hidden; -webkit-backface-visibility: hidden; backface-visibility: hidden;}

6. Open the bundleconfig.csfile under the app_startfile and use it to flip.css.

bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css", "~/Content/Flip.css"));

7. Press F5 to run the solution and log on.
8. Click any option to answer the question. Pay attention to the flip effect between the two views.

9. Click Next Question to extract the Next Question. The flip effect will also appear again.

Summary

By completing this hands-on lab, you have learned:
1. Use ASP. NET Scaffolding to create an ASP. NET Web API Controller
2. Implement the Get action of the Web API to extract the next quiz question
3. Implement the Post action of the Web API to store the quiz answer
4. Install AngularJS on the Package Manger Console of Visual Studio
5. Implement AngularJS templates and controllers
6. Use CSS3 transformations to execute action Effects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.