Part 30 AngularJS routeparams example

Here is what we want to do : When we navigate to /students, the list of student names must be displayed as hyperlinks.

When we click on any student name, the respective student details should be displayed as shown below. When we click on "Back to Students list" it should take us back to students list page.

Here are the steps to achieve this

Step 1 : The first step is to add a Web Method to our ASP.NET web service, which will retrieve student by their id. Add the following Web Method in StudentService.asmx.cs

[WebMethod]
public void GetStudent(int id)
{
    Student student = new Student();

    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(cs))
    {
        SqlCommand cmd = new
            SqlCommand("Select * from tblStudents where id = @id", con);

        SqlParameter param = new SqlParameter()
        {
            ParameterName = "@id",
            Value = id
        };

        cmd.Parameters.Add(param);

        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            student.id = Convert.ToInt32(rdr["Id"]);
            student.name = rdr["Name"].ToString();
            student.gender = rdr["Gender"].ToString();
            student.city = rdr["City"].ToString();
        }
    }

    JavaScriptSerializer js = new JavaScriptSerializer();
    Context.Response.Write(js.Serialize(student));
}

After adding the above method, the complete code in StudentService.asmx.cs should be as shown below.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace Demo
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class StudentService : System.Web.Services.WebService
    {
        [WebMethod]
        public void GetAllStudents()
        {
            List<Student> listStudents = new List<Student>();

            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("Select * from tblStudents", con);
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Student student = new Student();
                    student.id = Convert.ToInt32(rdr["Id"]);
                    student.name = rdr["Name"].ToString();
                    student.gender = rdr["Gender"].ToString();
                    student.city = rdr["City"].ToString();
                    listStudents.Add(student);
                }
            }

            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(listStudents));
        }

        [WebMethod]
        public void GetStudent(int id)
        {
            Student student = new Student();

            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new
                    SqlCommand("Select * from tblStudents where id = @id", con);

                SqlParameter param = new SqlParameter()
                {
                    ParameterName = "@id",
                    Value = id
                };

                cmd.Parameters.Add(param);

                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    student.id = Convert.ToInt32(rdr["Id"]);
                    student.name = rdr["Name"].ToString();
                    student.gender = rdr["Gender"].ToString();
                    student.city = rdr["City"].ToString();
                }
            }

            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(student));
        }
    }
}

Step 2 : Change the HTML in students.html partial template as shown below. Notice student name is now wrapped in an anchor tag. This will display student name as a hyperlink. If you click on a student name with id = 1, then we will be redirected to /students/1

<h1>List of Students</h1>
<ul>
    <li ng-repeat="student in students">
        <a href="students/{{student.id}}">
            {{student.name}}
        </a>
    </li>
</ul>

Step 3 : Now let‘s create an angularjs route with parameters. Add the following route inscript.js file. Our next step is to create studentDetails.html partial template andstudentDetailsController.

.when("/students/:id", {
    templateUrl: "Templates/studentDetails.html",
    controller: "studentDetailsController"
})

With the above change, the code in script.js should now look as shown below. Please pay attention to the code highlighted in yellow.

/// <reference path="angular.min.js" />
/// <reference path="angular-route.min.js" />

var app = angular
            .module("Demo", ["ngRoute"])
            .config(function ($routeProvider, $locationProvider) {
                $routeProvider
                    .when("/home", {
                        templateUrl: "Templates/home.html",
                        controller: "homeController"
                    })
                    .when("/courses", {
                        templateUrl: "Templates/courses.html",
                        controller: "coursesController"
                    })
                    .when("/students", {
                        templateUrl: "Templates/students.html",
                        controller: "studentsController"
                    })
                    .when("/students/:id", {
                        templateUrl: "Templates/studentDetails.html",
                        controller: "studentDetailsController"
                    })
                    .otherwise({
                        redirectTo: "/home"
                    })
                $locationProvider.html5Mode(true);
            })
            .controller("homeController", function ($scope) {
                $scope.message = "Home Page";
            })
            .controller("coursesController", function ($scope) {
                $scope.courses = ["C#", "VB.NET", "ASP.NET", "SQL Server"];
            })
             .controller("studentsController", function ($scope, $http) {
                 $http.get("StudentService.asmx/GetAllStudents")
                                        .then(function (response) {
                                            $scope.students = response.data;
                                        })

             })
 

Step 4 : Right click on Templates folder in solution explorer and add a new HTMLpage. Name it studentDetails.html. Copy and paste the following HTML.

<h1>Student Details</h1>

<table style="border:1px solid black">
    <tr>
        <td>Id</td>
        <td>{{student.id}}</td>
    </tr>
    <tr>
        <td>Name</td>
        <td>{{student.name}}</td>
    </tr>
    <tr>
        <td>Gender</td>
        <td>{{student.gender}}</td>
    </tr>
    <tr>
        <td>City</td>
        <td>{{student.city}}</td>
    </tr>
</table>
<h4><a href="students">Back to Students list</a></h4>

Step 5 : Add studentDetailsController in script.js which calls GetStudent web method and returns the requested student data.

.controller("studentDetailsController", function ($scope, $http, $routeParams) {
    $http({
        url: "StudentService.asmx/GetStudent",
        method: "get",
        params: { id: $routeParams.id }
    }).then(function (response) {
        $scope.student = response.data;
    })
})

With the above change, the code in script.js should now look as shown below. Please pay attention to the code highlighted in yellow.

/// <reference path="angular.min.js" />
/// <reference path="angular-route.min.js" />

var app = angular
            .module("Demo", ["ngRoute"])
            .config(function ($routeProvider, $locationProvider) {
                $routeProvider
                    .when("/home", {
                        templateUrl: "Templates/home.html",
                        controller: "homeController"
                    })
                    .when("/courses", {
                        templateUrl: "Templates/courses.html",
                        controller: "coursesController"
                    })
                    .when("/students", {
                        templateUrl: "Templates/students.html",
                        controller: "studentsController"
                    })
                    .when("/students/:id", {
                        templateUrl: "Templates/studentDetails.html",
                        controller: "studentDetailsController"
                    })
                    .otherwise({
                        redirectTo: "/home"
                    })
                $locationProvider.html5Mode(true);
            })
            .controller("homeController", function ($scope) {
                $scope.message = "Home Page";
            })
            .controller("coursesController", function ($scope) {
                $scope.courses = ["C#", "VB.NET", "ASP.NET", "SQL Server"];
            })
             .controller("studentsController", function ($scope, $http) {
                 $http.get("StudentService.asmx/GetAllStudents")
                                        .then(function (response) {
                                            $scope.students = response.data;
                                        })
             })
            .controller("studentDetailsController", function ($scope, $http, $routeParams) {
                $http({
                    url: "StudentService.asmx/GetStudent",
                    method: "get",
                    params: { id: $routeParams.id }
                }).then(function (response) {
                    $scope.student = response.data;
                })
            })

时间: 2024-10-06 04:50:00

Part 30 AngularJS routeparams example的相关文章

挖SRC逻辑漏洞心得分享

文章来源i春秋 白帽子挖洞的道路还漫长的很,老司机岂非一日一年能炼成的. 本文多处引用了 YSRC 的 公(qi)开(yin)漏(ji)洞(qiao).挖SRC思路一定要广!!!!漏洞不会仅限于SQL注入.命令执行.文件上传.XSS,更多的可能是逻辑漏洞.信息泄露.弱口令.CSRF.本文着重分析逻辑漏洞,其他的表哥可能会分享更多的思路,敬请期待.当然Web程序也不仅限于网站程序,漏洞更多的可能是微信公众号端.APP应用程序等等下面总结一下自己的SRC挖洞思路(逻辑漏洞).SRC常见的逻辑漏洞类型

百度,宫颈癌和房和附件是房价将阿斯顿发

http://www.ebay.com/cln/vnqus-aoi2rh42/ebay/157776573019/2015.01.30 http://www.ebay.com/cln/vnqus-aoi2rh42/ebay/157776590019/2015.01.30 http://www.ebay.com/cln/vnqus-aoi2rh42/ebay/157776608019/2015.01.30 http://www.ebay.com/cln/vnqus-aoi2rh42/ebay/15

百度,换房间啊回复大花洒减肥哈的时间放假了圣诞节

http://www.ebay.com/cln/yous-ypfkprfc/ebay/157911546014/2015.01.30 http://www.ebay.com/cln/yous-ypfkprfc/ebay/157911557014/2015.01.30 http://www.ebay.com/cln/yous-ypfkprfc/ebay/157911568014/2015.01.30 http://www.ebay.com/cln/dinjag.bwlw17m/ebay/15814

日志文件cpm

08/30/14 11:19:29,856 INFO =============CDN BaseLib is starting......!================ pid = 5894 [src/main.cpp:417] 08/30/14 11:19:29,857 TRACE Enter InitThreadPool() [src/main.cpp:260] 08/30/14 11:19:29,857 TRACE Exit InitThreadPool() [src/main.cpp

30分钟快速掌握AngularJs

[后端人员耍前端系列]AngularJs篇:30分钟快速掌握AngularJs 一.前言 对于前端系列,自然少不了AngularJs的介绍了.在前面文章中,我们介绍了如何使用KnockoutJs来打造一个单页面程序,后面一篇文章将介绍如何使用AngularJs的开发一个单页面应用程序.在开始使用AngularJs开发SPA之前,我觉得有必要详细介绍下AngularJs所涉及的知识点.所有也就有了这篇文章. 二.AngularJs介绍 AngularJS是Google推出的一款Web应用开发框架.

angularjs路由传值$routeParams

AngularJS利用路由传值, 1.导包 <script src="angular.min.js"></script> <script src="angular-route.js"></script> 2.依赖注入ngRoute var myapp=angular.module("myapp",["ngRoute"]); 3.配置路由 myapp.config(function

[后端人员耍前端系列]AngularJs篇:30分钟快速掌握AngularJs

一.前言 对于前端系列,自然少不了AngularJs的介绍了.在前面文章中,我们介绍了如何使用KnockoutJs来打造一个单页面程序,后面一篇文章将介绍如何使用AngularJs的开发一个单页面应用程序.在开始使用AngularJs开发SPA之前,我觉得有必要详细介绍下AngularJs所涉及的知识点.所有也就有了这篇文章. 二.AngularJs介绍 AngularJS是Google推出的一款Web应用开发框架.它提供了一系列兼容性良好并可扩展的服务,包括数据绑定.DOM操作.MVC和依赖注

AngularJS 30分钟入门【转】

引用自:http://www.revillweb.com/tutorials/angularjs-in-30-minutes-angularjs-tutorial/,以下以作者的口吻翻译. 简介 我三年前开始使用 AngularJS,那时它还是一个新鲜的的未知的东西时候. 现在 AngularJS已经成为了一个最受欢迎的 JavaScript 框架之一,多亏了AngularJS 团队做出的努力. 这个教程使用的是1.3.4版本,将会涵盖非常基础东西,但是都是Google和我的使用经验中总结出来的

angularjs学习总结 详细教程(转载)

1 前言 前端技术的发展是如此之快,各种优秀技术.优秀框架的出现简直让人目不暇接,紧跟时代潮流,学习掌握新知识自然是不敢怠慢. AngularJS是google在维护,其在国外已经十分火热,可是国内的使用情况却有不小的差距,参考文献/网络文章也很匮乏.这里便将我学习AngularJS写成文档,一方面作为自己学习路程上的记录,另一方面也给有兴趣的同学一些参考. 首先我自己也是一名学习者,会以学习者的角度来整理我的行文思路,这里可能只是些探索,有理解或是技术上的错误还请大家指出:其次我特别喜欢编写小