Angular动态菜单用于MVC和WCF REST(未完)

来源链接

http://www.codeproject.com/Articles/996614/Angular-JS-Dynamic-Menu-Creation-using-MVC-and-WCF

新手翻译,看到一些好文,将其转过来,希望能对大家起到一点点的帮助.

1,为什么我们需要动态创建菜单:


如果我们只是需要创建一个只有几个页面的网站,那么用静态菜单就可以。

但是只果要开发一个大型Web应用的话,例如ERP Web应用.

在这种情况下,会有2个以上的开发者一起工作,而且页面可能会超过50-100个,这种情况下,用静态菜单将会是一个很大的挑战.

而且在开发中或之后,我们的客户可能会要求我们增加5个新的菜单,或移除掉一个菜单元素.

在使用静态菜单的情形下,这将会是一个很耗时的操作.

而且在开发大型Web项目时,比如ERP,我们需要基于用于角色来显示菜单,如果我们使用静态菜单的话,这将会一

件很难成.

为了解决这些情况,我们应该基于用于角色配置来创建菜单

谁应该管理这些菜单?

这是非常重要的部分,例如管理或超级用户可以 添加/编辑/删除 这些菜单或用户.

当管理员登录后,他能添加新菜单,编辑现有菜单和删除菜单元素。

这篇文章的关注点并不在于菜单管理而在于如何创建一个主菜单和菜单详情表,Insert一些示例菜单进我们的数据表,然后在我们的MVC Web页上使用AngularJS 和WCF Rest服务来动态的显示它.

这篇文章将会说胆:

1,如何创建一个WCF Rest服务和从数据库中查询数据

2,如何安装Angular JS Package进MVC 应用.

3,如何使用Angular JS建立一个动态菜单应用.

4,如何在Angular JS里使用WCS 服务显示动态菜单

注意:你首先必须安装Visual Studio 2013

Here we can see some basics and reference links for Windows Communication Foundation (WCF). WCF is a framework for building service-oriented applications.

Service-oriented application: Using this protocol the service can be shared and used over a network.

For example let‘s consider now we are working on a project and we need to create some common database function and those functions need to be used in multiple projects and the projects are in multiple places and connected via a network such as the internet.

In this case we can create a WCF service and we can write all our common database functions in our WCF service class. We can deploy our WCF in IIS and use the URL in our application to do DB functions. In the code part let‘s see how to create a WCF REST service and use it in our AngularJS application.

If you are interested in reading more details about WCF then kindly go to this link.

AngularJS 

We might be be familiar with what Model, View and View Model (MVVM) is and what Model, View and Controller (MVC) is. AngularJS is a JavaScript framework that is purely based on HTML CSS and JavaScript.

Similar to the MVC and MVVM patterns AngularJS uses the Model, View and Whatever (MVW) pattern.

In our example I have used a Model, View and Service. In the code part let‘s see how to install and create AngularJS in our MVC application.

If you are interested in reading more details about WCF then kindly go to this link.

Using the code

We will create a MenuMaster and MenuDetails table under the Database MenuDB.

Note: The MenuMaster and MenuDetail or the important tables which will be used to load our menu dynamically. We need to understand how to insert menu details to these tables to display our menu properly.

In this article I have display 3 Level hierarchical display of menu here you can see the 3 level hierarchical sample.

Here we can see 1 Level hierarchy-> Inventory;

2nd Level hierarchy-> inventory Details

3rd Level hierarchy-> Finished Goods Receipt and Finished Goods Issue.

Now let’s see how we create table relationship to create the master and detail menu.

Menu Master Table

1 Level hierarchy Insert

Hide   Copy Code

Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Root‘,‘Inventory‘,‘Shanu‘,getdate()-23)

2 Level hierarchies Insert

Hide   Copy Code

Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Inventory‘,‘INV001‘,‘Shanu‘,getdate()-23)

3 Level hierarchies Insert

Hide   Copy Code

Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘INV001‘,‘FG001‘,‘Shanu‘,getdate()-23)

Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘INV001‘,‘FG002‘,‘Shanu‘,getdate()-23)

Menu Detail Table

1 Level hierarchy Insert

Hide   Copy Code

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,

MenuURL,UserID,CreatedDate)

values(‘Inventory‘,‘Inventory‘,‘Inventory‘,‘Index‘,‘Inventory‘,

‘Shanu‘,getdate()-23)

2 Level hierarchies Insert

Hide   Copy Code

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,

MenuURL,UserID,CreatedDate)

values(‘INV001‘,‘Inventory‘,‘Inventory Details‘,‘Index‘,‘Inventory‘,

‘Shanu‘,getdate()-23)

3 Level hierarchies Insert

Hide   Copy Code

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,

MenuURL,UserID,CreatedDate)

values(‘FG001‘,‘FGIN‘,‘FG Receipt‘,‘FGIN‘,‘Inventory‘,‘Shanu‘,getdate()-43)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,

MenuURL,UserID,CreatedDate)

values(‘FG002‘,‘FGOUT‘,‘FG Issue‘,‘FGOUT‘,‘Inventory‘,‘Shanu‘,getdate()-13)

Here we can see Field used for Menu Detail I have used the fields

Here we can see field used for Menu Master I have used the fields

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 2012.

Hide   Shrink    Copy Code

-- =============================================
-- Author      : Shanu
-- Create date : 2015-03-20
-- Description : To Create Database,Table and Sample Insert Query
-- Latest
-- Modifier    : Shanu
-- Modify date : 2015-03-20
-- =============================================
--Script to create DB,Table and sample Insert data
USE MASTER
GO
-- 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] = ‘MenuDB‘ )
DROP DATABASE MenuDB
GO

CREATE DATABASE MenuDB
GO
USE MenuDB
GO

-- 1) //////////// ToysDetails table
-- Create Table  ToysDetails ,This table will be used to store the details like Toys Information

IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = ‘MenuMaster‘ )
DROP TABLE MenuMaster
GO
CREATE TABLE MenuMaster
(
   Menu_ID int identity(1,1),
   Menu_RootID VARCHAR(30)  NOT NULL,
   Menu_ChildID VARCHAR(30)  NOT NULL,
   UserID varchar(50),
   CreatedDate datetime
CONSTRAINT [PK_MenuMaster] PRIMARY KEY CLUSTERED
(
  [Menu_ID] ASC   ,
  [Menu_RootID] ASC,
  [Menu_ChildID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
--delete from MenuMaster
-- Insert the sample records to the ToysDetails Table
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Root‘,‘Home‘,‘Shanu‘,getdate()-23)
--Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Home‘,‘Home‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Home‘,‘About‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Home‘,‘Contact‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Root‘,‘Masters‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Masters‘,‘ITM001‘,‘Shanu‘,getdate()-23)
--Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘ITM001‘,‘ITM001‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘ITM001‘,‘ITM002‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘ITM001‘,‘ITM003‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Masters‘,‘CAT001‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘CAT001‘,‘CAT001‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘CAT001‘,‘CAT002‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘CAT001‘,‘CAT003‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Root‘,‘Inventory‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘Inventory‘,‘INV001‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘INV001‘,‘FG001‘,‘Shanu‘,getdate()-23)
Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values(‘INV001‘,‘FG002‘,‘Shanu‘,getdate()-23)

select * from MenuMaster
-- 1) END //

-- 2) Cart Details Table
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = ‘MenuDetails‘ )
DROP TABLE MenuDetails
GO

CREATE TABLE MenuDetails
(
   MDetail_ID int identity(1,1),
   Menu_ChildID VARCHAR(20) NOT NULL,
   MenuName VARCHAR(100) NOT NULL,
   MenuDisplayTxt VARCHAR(200) NOT NULL,
   MenuFileName VARCHAR(100) NOT NULL,
   MenuURL VARCHAR(500) NOT NULL,
   USE_YN Char(1) DEFAULT ‘Y‘,
   UserID varchar(50),
   CreatedDate datetime
CONSTRAINT [PK_MenuDetails] PRIMARY KEY CLUSTERED
(
  [MDetail_ID] ASC,
  [Menu_ChildID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

----delete from MenuDetails

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘Root‘,‘Home‘,‘Shanu Home‘,‘Index‘,‘Home‘,‘Shanu‘,getdate()-23)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘Home‘,‘Home‘,‘Shanu Home‘,‘Index‘,‘Home‘,‘Shanu‘,getdate()-23)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘About‘,‘About‘,‘About Shanu‘,‘About‘,‘Home‘,‘Shanu‘,getdate()-43)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘Contact‘,‘Contact‘,‘Contact Shanu‘,‘Contact‘,‘Home‘,‘Shanu‘,getdate()-13)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘Masters‘,‘Masters‘,‘Masters‘,‘ItemDetails‘,‘Masters‘,‘Shanu‘,getdate()-13)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘ITM001‘,‘ItemMaster‘,‘Item Master‘,‘ItemDetails‘,‘Masters‘,‘Shanu‘,getdate()-13)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘ITM002‘,‘ItemDetail‘,‘Item Details‘,‘ItemDetails‘,‘Masters‘,‘Shanu‘,getdate()-13)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘ITM003‘,‘ItemManage‘,‘Item Manage‘,‘ItemManage‘,‘Masters‘,‘Shanu‘,getdate()-13)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘CAT001‘,‘CatMaster‘,‘Category Masters‘,‘CATDetails‘,‘Masters‘,‘Shanu‘,getdate()-13)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘CAT002‘,‘CATDetail‘,‘Category Details‘,‘CATDetails‘,‘Masters‘,‘Shanu‘,getdate()-13)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘CAT003‘,‘CATManage‘,‘Category Manage‘,‘CATManage‘,‘Masters‘,‘Shanu‘,getdate()-13)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘Inventory‘,‘Inventory‘,‘Inventory‘,‘Index‘,‘Inventory‘,‘Shanu‘,getdate()-23)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘INV001‘,‘Inventory‘,‘Inventory Details‘,‘Index‘,‘Inventory‘,‘Shanu‘,getdate()-23)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘FG001‘,‘FGIN‘,‘FG Receipt‘,‘FGIN‘,‘Inventory‘,‘Shanu‘,getdate()-43)

Insert into MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)
values(‘FG002‘,‘FGOUT‘,‘FG Issue‘,‘FGOUT‘,‘Inventory‘,‘Shanu‘,getdate()-13)

select * from MenuMaster

select * from MenuDetails

             select   A.Menu_RootID,
                 B.MDetail_ID,
                 B.Menu_ChildID,
                 B.MenuName,
                 B.MenuDisplayTxt,
                 B.MenuFileName,
                 B.MenuURL ,
                 B.UserID
                 FROM
                 MenuMaster A
                 INNER JOIN MenuDetails B
                 ON A.Menu_ChildID=B.Menu_ChildID

2) Create WCF REST Service:

Open Visual Studio 2013 then select "File" -> "New" -> "Project..." then select WCF Service Application then select your project path and name your WCF service and click OK.

Once we have created our WCF Service we can see “IService.CS” and “Service1.svc” in the Solution Explorer as in the following.

  • IService.CS: In “IService.CS” we can see 3 Contracts by defaul.
  • [ServiceContract]: Describes the methods or any operations available for the service. The Service Contract is an interface and methods can be declared inside the Service Interface using the Operation Contract attribute.
  • [OperationContract]: is similar to the web service [WEBMETHOD].
  • [DataContract]: describes the data exchange between the client and the service.
  • [ServiceContract]

The following code will be automatically created for all the IService.CS files. We can change and write our own code here.

Hide   Shrink    Copy Code

    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }
 // Use a data contract as illustrated in the sample below to add composite types to service operations.

    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }

Data Contract

In our example we need to get all Menu Details from the database, so I have created a Data Contracts, “MenuDataContract” Here we can see we have decelerated our entire Table column name as Data Member.

Hide   Shrink    Copy Code

public class MenuDataContract    {
        [DataContract]
        public class MenuMasterDataContract
        {
            [DataMember]
            public string Menu_ID { get; set; }

            [DataMember]
            public string Menu_RootID { get; set; }

            [DataMember]
            public string Menu_ChildID { get; set; }

            [DataMember]
            public string UserID { get; set; }
        }

        [DataContract]
        public class MenuDetailDataContract
        {
            [DataMember]
            public string MDetail_ID { get; set; }

            [DataMember]
            public string Menu_RootID { get; set; }

            [DataMember]
            public string Menu_ChildID { get; set; }

            [DataMember]
            public string MenuName { get; set; }

            [DataMember]
            public string MenuDisplayTxt { get; set; }

            [DataMember]
            public string MenuFileName { get; set; }

            [DataMember]
            public string MenuURL { get; set; }

            [DataMember]
            public string UserID { get; set; }
        }
    }

Service Contract

In the Operation Contract we can see “WebInvoke” and “WebGet” for retrieving the data from the database in the REST Serivce.

     RequestFormat = WebMessageFormat.Json,

   ResponseFormat = WebMessageFormat.Json,

Here we can see both of the request and response formats. Here I have used the JavaScript Object Notation (JSON) format.

  • JSON is a lightweight data interchange format.
  • UriTemplate: Here we provide our Method Name.

Here I have declared the 3 methods “GetMenuDetails” . The “GetMenuDetails” method gets all Menu Master and Details which will be used in our AngularJs to display the menu using filter for each hierarchy..

Hide   Copy Code

 [ServiceContract]

    public interface IService1

    {

[OperationContract]

        [WebInvoke(Method = "GET",

           RequestFormat = WebMessageFormat.Json,

           ResponseFormat = WebMessageFormat.Json,

           UriTemplate = "/GetMenuDetails/")]

        List<MenuDataContract.MenuDetailDataContract> GetMenuDetails();

 }

Iservice.Cs -> Complete Source Code

Hide   Shrink    Copy Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace ShanuMenuCreation_WCF
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/GetMenuDetails/")]
        List<MenuDataContract.MenuDetailDataContract> GetMenuDetails();
        // TODO: Add your service operations here
    }

 // Use a data contract as illustrated in the sample below to add composite types to service operations.
    public class MenuDataContract
    {
        [DataContract]
        public class MenuMasterDataContract
        {
            [DataMember]
            public string Menu_ID { get; set; }

            [DataMember]
            public string Menu_RootID { get; set; }

            [DataMember]
            public string Menu_ChildID { get; set; }

            [DataMember]
            public string UserID { get; set; }
        }

        [DataContract]
        public class MenuDetailDataContract
        {
            [DataMember]
            public string MDetail_ID { get; set; }

            [DataMember]
            public string Menu_RootID { get; set; }

            [DataMember]
            public string Menu_ChildID { get; set; }

            [DataMember]
            public string MenuName { get; set; }

            [DataMember]
            public string MenuDisplayTxt { get; set; }

            [DataMember]
            public string MenuFileName { get; set; }

            [DataMember]
            public string MenuURL { get; set; }

            [DataMember]
            public string UserID { get; set; }
        }
    }
}

Add Database using ADO.NET Entity Data Model

Right-click your WCF project and select Add New Item tehn select ADO.NET Entity Data Model and click Add.

Select EF Designer from Database and click next.

Click New Connection

Here we can select our Database Server Name and enter your DB server SQL Server Authentication User ID and Password. We have already created our data base as “MenuDB” so we can select the database and click ok.

Click next and select our tables need to be used and click finish.

Here we can see now we have created our ShanuMenuModel.

Service1.SVC

“Service.SVC.CS” implements the IService Interface and overrides and defines all the methods of the Operation Contract. For For example here we can see I have implemented the IService1 in the Service1 class. Created the object for our Entity model and in GetMenuDetails using a LINQ join query I get both Menu Master and Detail datas.

Hide   Shrink    Copy Code

public class Service1 : IService1
    {
        ShanuMenuCreation_WCF.MenuDBEntities OME;

        public Service1()
        {
            OME = new ShanuMenuCreation_WCF.MenuDBEntities();
        }

        public List<MenuDataContract.MenuDetailDataContract> GetMenuDetails()
        {
            ////var query = (from a in OME.MenuDetails
            ////             select a).Distinct();
             var query = (from A in OME.MenuMaster
                         join B in OME.MenuDetails on A.Menu_ChildID equals B.Menu_ChildID
                         select new
                         {
                            A.Menu_RootID,
                            B.MDetail_ID,
                            B.Menu_ChildID,
                            B.MenuName,
                            B.MenuDisplayTxt,
                            B.MenuFileName,
                            B.MenuURL ,
                            B.UserID
                         }).ToList().OrderBy(q => q.MDetail_ID); 

            List<MenuDataContract.MenuDetailDataContract> MenuList = new List<MenuDataContract.MenuDetailDataContract>();

            query.ToList().ForEach(rec =>
            {
                MenuList.Add(new MenuDataContract.MenuDetailDataContract
                {
                    MDetail_ID = Convert.ToString(rec.MDetail_ID),
                    Menu_RootID = rec.Menu_RootID,
                    Menu_ChildID = rec.Menu_ChildID,
                    MenuName = rec.MenuName,
                    MenuDisplayTxt = rec.MenuDisplayTxt,
                    MenuFileName = rec.MenuFileName,
                    MenuURL = rec.MenuURL,
                    UserID = rec.UserID,
                });
            });
            return MenuList;
       }
    }

Web.Config:

In WCF project “Web.Config” Change the

1) Change <add binding="basicHttpsBinding" scheme="https" /> to <add binding="webHttpBinding" scheme="http" />

2) Replace the </behaviors> to

Hide   Copy Code

<endpointBehaviors>
        <behavior>
          <webHttp helpEnabled="True"/>
        </behavior>
      </endpointBehaviors>   

Run WCF Service: -> Now we have created our WCF Rest service, let‘s run and test our service. In our service URL we can add our method name and we can see the JSON result data from the database.

Create MVC Web Application

So now we have completed our WCF and now it‘s time to create our MVC AngularJS application.We can add a new project to our existing project and create a new MVC web application as in the following.Right-click the project in the solution and click Add New Project then enter your project name and click "OK".

Select MVC and click "OK".

Now we have created our MVC application and it‘s time to add our WCF Service and install the AngularJS package to our solution.
Add WCF Service: Right-click MVC Solution and click Add then click Service Reference.

Enter your WCF URL and click GO .here my WCF URL is http://localhost:3514/Service1.svc/

Add your name and click ok.

Now we have successfully added our WCF Service to our MVC Application.

Steps to Install Angular JS package

Right Click your MVC project and Click-> Manage NuGet Packages

Select Online and Search for Angular JS. Select the AngularJs and click Install.

Now we have Installed the AngularJS package into our MVC Project. Now let‘s create our AngularJs.

  • Modules.js
  • Controllers.js
  • Services.js

Procedure to Create AngularJs Script Files

Right-click the Script folder and create your own folder to create the AngularJs Model/Controller and Service JavaScript. In your script folder add three JavaScript files and name them Modules.js, Controllers.js and Services.js as in the following.

Modules.js: Here we add the reference to the Angular.js JavaScript.we give our module name as “RESTClientModule” .

Hide   Copy Code

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

var app;
(function () {
    app = angular.module("RESTClientModule", []);
})();

Services.js: Here we provide a name for our service and we use this name in shanucontroller.js. Here for the Angular service I have given the name "AngularJs_WCFService". You can give your own name but be careful of changing the name in Controllers.js. Angularjs can receive json data; here we can see I have provided our WCS service URL to get the Item details as JSON data. To insert Item information result to Database we pass the data as JSON data to our WCF insert method as parameter.

Hide   Copy Code

/// <reference path="../angular.js" />
/// <reference path="../angular.min.js" />
/// <reference path="Modules.js" />    

app.service("AngularJs_WCFService", function ($http) {
    //Get Order Master Records
    this.geMenuDetails = function () {
        return $http.get("http://localhost:3514/Service1.svc/GetMenuDetails");
    };
});

AngularJs Controller: Here we add the reference to the Angular.js JavaScript , our Module.js and Services.js. The same as for services. For the controller I have given the name "AngularJsShanu_WCFController". In the Controller I have done all the business logic and returned the data from the WCF JSON data to our MVC HTML page.

1) Variable declarations

First I declared all the local variables that need to be used and the current date and store the date using $scope.date.

Note: $scope.subChildIDS = "ITM001"; this variable has been used to filter the 2nd level hierarchy.

2) Methods

getAllMenuDetails() : In this method I will get all the Menu Detail as JSON and bind the result to the Main page.

$scope.showsubMenu = function (showMenus,ids) {}In this method on mouse over I will filter the 2nd level hierarchy menu details and add the menu items to the list.

shanuController.js full source code

Hide   Shrink    Copy Code

/// <reference path="../angular.js" />
/// <reference path="../angular.min.js" />
/// <reference path="Modules.js" />
/// <reference path="Services.js" />  

app.controller("AngularJsShanu_WCFController", function ($scope, $window, AngularJs_WCFService) {
    $scope.date = new Date();
    $scope.showDetails = false;
    $scope.showSubDetails = false;
    $scope.subChildIDS = "ITM001";
    $scope.Imagename = "R1.png";
    getAllMenuDetails();
    //To Get All Records
    function getAllMenuDetails() {
        var promiseGet = AngularJs_WCFService.geMenuDetails();
        promiseGet.then(function (pl) {
            $scope.MenuDetailsDisp = pl.data
        },
             function (errorPl) {
             });
    }

    $scope.showMenu = function (showMenus) {

        if (showMenus == 1) {
            $scope.Imagename = "R2.png"
            $scope.showDetails = true;
        }
        else {
            $scope.Imagename = "R1.png"
            $scope.showDetails = false;
        }
    }

    $scope.showsubMenu = function (showMenus,ids) {    

        if (showMenus == 1) {
            $scope.subChildIDS = ids;
            $scope.showSubDetails = true;
        }
        else if(showMenus == 0) {
            $scope.showSubDetails = false;
        }
        else {
           $scope.showSubDetails = true;
        }
    }
});

So now we have created our Angular Js Module /Controller and Service. So what is next?

Create MVC Control and View to display our result.
Add Controller
Right-click Controllers then select Add Controller then select MVC 5 Controller –Empty then click Add.

Hide   Copy Code

public class MastersController : Controller
    {
        // GET: Masters
        public ActionResult Index()
        { return View(); }

        public ActionResult ItemDetails()
        { return View(); }

        public ActionResult ItemManage()
        { return View(); }
        public ActionResult CATDetails()
        { return View(); }

        public ActionResult CATManage()
        { return View(); }
    }

Add one more controller as InventoryController

Hide   Copy Code

public class InventoryController : Controller
    {
        // GET: Inventory
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult FGIN()
        {
            return View();
        }
        public ActionResult FGOUT()
        {
            return View();
        }

    }

1) Index View

Name the View “Index”.

In the View, design your page and reference angular.Js, Modules.js, Services.js and Controllers.js.

In Angular JS we use {{ }} to bind or display the data.

Here we can see that I first created a table and something for that table.

First the in table I used the data-ng-controller="AngularJsShanu_WCFController" and here we can see data-ng-controller will be used to bind the data of the controller to the HTML table.

Using < li data-ng-repeat="menus in MenuDetailsDisp | filter:{Menu_RootID:‘Root‘}" > we can get all the  menu details and display the First Level hierarchy menu details as top menu.

Here we can see I have used the Filter the menu by rootId with ‘Root’. During our insert query I have already explained for every top level menu I will give the Rootid as ‘Root’. First we add all the top level menu and for each top level menu if there is any 2nd level hierarchies I will load the 2nd level menu details filter by 1st level RootID  as below.

Hide   Copy Code

<li data-ng-repeat="menus in MenuDetailsDisp | filter:{Menu_RootID:‘Root‘}">
                                        @{
                                            var url = Url.Action("{{menus.MenuFileName}}", "{{menus.MenuURL}}", new { id = "{{id=menus.MenuURL}}" });
                                            url = HttpUtility.UrlDecode(url);
                                        }
                                        <a data-ng-href="@url">{{menus.MenuDisplayTxt}}</a>
                                        <ul class="sub-menu">
                                            <li data-ng-repeat="submenus in MenuDetailsDisp | filter:{Menu_RootID:menus.Menu_ChildID}" ng-mouseover="showsubMenu(1,submenus.Menu_ChildID);" ng-mouseout="showsubMenu(0,submenus.Menu_ChildID);">
                                                @{
                                                    var url1 = Url.Action("{{submenus.MenuFileName}}", "{{submenus.MenuURL}}", new { id = "{{id=submenus.MenuURL}}" });
                                                    url1 = HttpUtility.UrlDecode(url1);
                                                }
                                                <a data-ng-href="@url1">{{submenus.MenuDisplayTxt}}</a>

Here we can see for the 2nd level hierarchy I have filtered by data-ng-repeat="submenus in MenuDetailsDisp | filter :{Menu_RootID:menus.Menu_ChildID}" where menus.Menu_ChildID is the top level menu id.

Same like this for 3rd level Hierarchy I will give the 2nd level hierarchy root id as below.

Hide   Shrink    Copy Code

<div style="overflow:visible;height:100px;">
                                <ul class="menu">
                       <li data-ng-repeat="menus in MenuDetailsDisp | filter:{Menu_RootID:‘Root‘}">
                                        @{
                                            var url = Url.Action("{{menus.MenuFileName}}", "{{menus.MenuURL}}", new { id = "{{id=menus.MenuURL}}" });
                                            url = HttpUtility.UrlDecode(url);
                                        }
                                        <a data-ng-href="@url">{{menus.MenuDisplayTxt}}</a>
                                        <ul class="sub-menu">
                                            <li data-ng-repeat="submenus in MenuDetailsDisp | filter:{Menu_RootID:menus.Menu_ChildID}" ng-mouseover="showsubMenu(1,submenus.Menu_ChildID);" ng-mouseout="showsubMenu(0,submenus.Menu_ChildID);">
                                                @{
                                                    var url1 = Url.Action("{{submenus.MenuFileName}}", "{{submenus.MenuURL}}", new { id = "{{id=submenus.MenuURL}}" });
                                                    url1 = HttpUtility.UrlDecode(url1);
                                                }
                                                <a data-ng-href="@url1">{{submenus.MenuDisplayTxt}}</a>
                                                <ul ng-show="showSubDetails" class="sub-menu2">
                                                    <li data-ng-repeat="sub1menus in MenuDetailsDisp  | filter:{Menu_RootID:subChildIDS}" ng-mouseover="showsubMenu(3,9);">
                                                        @{
                                                            var url2 = Url.Action("{{sub1menus.MenuFileName}}", "{{sub1menus.MenuURL}}", new { id = "{{id=sub1menus.MenuURL}}" });
                                                            url2 = HttpUtility.UrlDecode(url2);
                                                        }
                                                        <a data-ng-href="@url2">{{sub1menus.MenuDisplayTxt}}</a>
                                                    </li>
                                                </ul>
                                            </li>
                                        </ul>
                                    </li>
                                </ul>
                            </div>

Run the Program

时间: 2024-10-28 20:36:29

Angular动态菜单用于MVC和WCF REST(未完)的相关文章

WIN 下的超动态菜单(二)用法

WIN 下的超动态菜单(一)简介 作者:黄山松,发表于博客园:http://www.cnblogs.com/tomview/         auto_dynamenu 是一个动态生成WINDOWS菜单的c++封装库,设计思路是要尽量简化动态菜单的生成代码,在程序界面任何地方想要显示菜单(特别是右键菜单)的时候,可以方便生成菜单,特别可以根据程序当时的内部数据,内部状态来生成不同的动态菜单.         auto_dynamenu 只封装了一个静态的接口函数,这样处理的目的是把类的实现代码可

游刃于MVC、WCF中的Autofac

为了程序的健壮性.扩展性.可维护性,依赖抽象而不是具体实现类等等,于是我选择了Autofac依赖注入容器 就是这个工厂来降低耦合.之前买东西是自己去超市,现在呢 我需要什么东西,他们给送过来直接拿到了.  本例中将会分享 1.Autofac在Mvc的Controller控制器.Filter过滤器的使用 2.WCF中的使用 3.用Autofac来完成Unit Of Work工作单元模式 即同一个界限上下文内可以共享同一个工作单元实例.这样就可以统一提交,起到事务作用.数据统一性.一个http请求只

Django项目:CRM(客户关系管理系统)--82--72PerfectCRM实现CRM动态菜单和角色

1 #models.py 2 3 # --------01PerfectCRM基本配置ADMIN-------- 4 5 from django.db import models 6 # Create your models here. 7 8 """ 9 #运行 Terminal 10 # 生成 数据表 11 # python manage.py makemigrations 12 # 数据表 迁移 13 # python manage.py migrate 14 &quo

Angular动态创建组件之Portals

这篇文章主要介绍使用Angular api 和 CDK Portals两种方式实现动态创建组件,另外还会讲一些跟它相关的知识点,如:Angular多级依赖注入.ViewContainerRef,Portals可以翻译为 门户 ,我觉得放到这里叫 入口 更好,可以理解为动态创建组件的入口,类似于小程序或者Vue中的Slot. cdk全名Component Development Kit 组件开发包,是Angular官方在开发基于Material Design的组件库时抽象出来单独的一个开发包,里面

abp添加动态菜单

abp中MenuDefinition封装了导航栏上的主菜单的属性,MenuItemDefinition则封装了子菜单的属性,子菜单可以引用其他子菜单构成一个菜单树. MenuDefinitio成员如下: public object CustomData { get; set; }//自定义数据 public ILocalizableString DisplayName { get; set; }//表示本地化字符串 public IList<MenuItemDefinition> Items

获取iframe(angular 动态页面)高度

问题比较特殊,google了好久才得到启示 开发的angular页面,需要嵌入到客户的web页中,以iframe方式.由于iframe的高度需要指定,而angular动态生成机制导致页面高度会随时变化, 就会出现2个滚动条,一个是页面本身,一个是iframe里的. 解决方法如下: 1.写一个directive监听angular的$digest,实时获取body高度,通过 HTML5 postMessage方式传出 在HTML5中新增了postMessage方法,postMessage可以实现跨文

Android 基于TranslateAnimation 的动画动态菜单(非系统menu菜单)

先请注意,这里的菜单并不是按机器上的 MENU出现在那种菜单,而是基于Android SDK 提供的 android.view.animation.TranslateAnimation(extends android.view.animation.Animation)类实例后附加到一个 Layout 上使之产生的有动画出现和隐藏效果的菜单. 原理:Layout(菜单)从屏幕内(挨着屏幕边沿,其实并非一定,视需要的初态和末态而定)动态的移动到屏幕外(在外面可以挨着边沿,也可以离远点,这个无所谓了)

Java动态菜单添加

自己做出来的添加数据库配置好的动态菜单的方法 private void createMenu() {  IMenuDAO dao = new MenuDAOImpl();  String sql1 = "select * from menu where menuId like '__'";  String sql2 = "select * from menu where menuId like '____'";  //记住这里是用的自己写的实体Menu,而不是Jav

JS打字效果的动态菜单代码分享

这篇文章主要介绍了JS打字效果的动态菜单,推荐给大家,有需要的小伙伴可以参考下. 这是一款基于javascript实现的打字效果的动态菜单特效代码,分享给大家学习学习. 小提示:浏览器中如果不能正常运行,可以尝试切换浏览模式.为大家分享的JS打字效果的动态菜单代码如下 <html> <head> <title>JS打字效果的动态菜单</title> <meta http-equiv="imagetoolbar" content=&q