AngularMaterial Tutorial With MVC

Introduction

In my previous articles, I explained a lot about Angular.js; i.e., how to save, update, delete, get, paging searching, sorting etc. In this article, we talk about the new library of Angular.js; i.e, Angular material .

Here a question arises. What is Angular material and how to use it ?

Answer 

Angular material is a component library of Angular.JS that is used to create attractive, responsive Web pages; that is the need of today's standards.

Angular material's built in responsive features helps us to create the Website irrespective of any devices. The Website runs on all the devices - either it is a desktop or a mobile. It automatically adjusts itself on the screen accordingly.

Angular material provides almost all types of the controls with better designs -  either it is navigation bars or they are form inputs, everything is provided with Angular.js library.

sign in

Start creating the database

  • Create a database named Test.

  • Create a table Login in the database.

    table

Start with code

Basic setup

  • Open VS and create a new project.

  • Go to the reference folder in Solution Explorer and right click on the folder, select Manage NuGet Packages.

  • Install the Angular material and Angular.JS libraries online or download from the links, given below:

  • Open BundleConfig.cs file in App_Start folder.

  • Remove the code inside from RegisterBundles method. Don't remove the method.

Layout setup of the project

  • Open the Layout.cshtml file in shared folder of views.

  • Start writing code, as shown below:
    1. <!DOCTYPE html>  
    2. <html lang="en">  
    3.   
    4. <head>  
    5.     <meta charset="utf-8" />  
    6.     <title>@ViewBag.Title</title>  
    7.     <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />  
    8.     <meta name="viewport" content="width=device-width" />  
    9.     <link href="~/Content/angular-material.min.css" rel="stylesheet" />  
    10.     <script src="~/Scripts/angular.min.js"></script>  
    11.     <script src="~/Scripts/angular-animate/angular-animate.min.js"></script>  
    12.     <script src="~/Scripts/angular-aria/angular-aria.min.js"></script>  
    13.     <script src="~/Scripts/angular-messages.min.js"></script>  
    14.     <script src="~/Scripts/angular-material/angular-material.min.js"></script>  
    15. </head>  
    16.   
    17. <body>  
    18.     <div class="wrapper">  
    19.         <div class="container">  
    20.             @RenderBody()  
    21.         </div>  
    22.     </div>  
    23.     @RenderSection("scripts", required: false)  
    24. </body>  
    25.   
    26. </html>  
  • Here, in the head section, drag and drop the files whose links are given above.

UI Creation

  • Go to the Controller folder, create Register Controller.

  • Change the name of the Action Result index to register.

  • Right click on Action Result register and select addview option.

  • Go to the Register view that is created from register actionresult.

    Start writing code
    1. <html ng-app="myApp">  
    2.   
    3. <head>  
    4.     <title>Register</title>  
    5. </head>  
    6.   
    7. <body>  
    8.   
    9.     <div ng-controller="controll" layout="column" layout-padding ng-cloak>  
    10.         <br />  
    11.         <md-content class="md-no-momentum">  
    12.             <md-toolbar class="md-accent">  
    13.                 <h2 class="md-toolbar-tools">   
    14. <span flex>Register User</span>   
    15. </h2>  
    16.             </md-toolbar><br /><br />  
    17.             <form name="userForm">  
    18.                 <div layout-gt-sm="column" flex="30">  
    19.                     <md-input-container class="md-icon-float md-block">  
    20.                         <label>First Name</label>  
    21.                         <md-icon md-svg-src="~/Content/Icons/employee.svg" class="fName"></md-icon>  
    22.                         <input type="text" class="form-control" name="fName" ng-model="fName" required autofocus />  
    23.                         <div ng-messages="userForm.fName.$error">  
    24.                             <div ng-message="required">First name is required!</div>  
    25.                         </div>  
    26.                     </md-input-container>  
    27.                     <md-input-container class="md-icon-float md-block">  
    28.                         <label>Last Name</label>  
    29.                         <md-icon md-svg-src="~/Content/Icons/employee.svg" class="lName"></md-icon>  
    30.                         <input type="text" class="form-control" name="lName" ng-model="lName" required autofocus />  
    31.                         <div ng-messages="userForm.lName.$error">  
    32.                             <div ng-message="required">Last name is required !</div>  
    33.                         </div>  
    34.                     </md-input-container>  
    35.                 </div>  
    36.                 <div layout-gt-sm="column" flex="30">  
    37.                     <md-input-container class="md-icon-float md-block">  
    38.                         <label>Email</label>  
    39.                         <md-icon md-svg-src="~/Content/Icons/placeholder.svg" class="uEmail"></md-icon>  
    40.                         <input type="email" class="form-control" name="uEmail" ng-model="uEmail" ng-pattern="/^.+.+\..+$/" required autofocus />  
    41.                         <div ng-messages="userForm.uEmail.$error">  
    42.                             <div ng-message-exp="['required','pattern']">Email is required in correct format !</div>  
    43.                         </div>  
    44.                     </md-input-container>  
    45.   
    46.                     <md-input-container class="md-icon-float md-block">  
    47.                         <label>Username</label>  
    48.                         <md-icon md-svg-src="~/Content/Icons/placeholder.svg" class="uName"></md-icon>  
    49.                         <input type="text" class="form-control" name="uName" ng-model="uName" md-maxlength="8" required autofocus />  
    50.                         <div ng-messages="userForm.uName.$error">  
    51.                             <div ng-message="required">Username is required !</div>  
    52.                             <div ng-message="md-maxlength">Maximum 8 characters allowed !</div>  
    53.                         </div>  
    54.                     </md-input-container>  
    55.                 </div>  
    56.                 <div layout-gt-sm="column" flex="30">  
    57.                     <md-input-container class="md-icon-float md-block" flex-gt-sm>  
    58.                         <label>Password</label>  
    59.                         <md-icon md-svg-src="~/Content/Icons/cityscape.svg" class="uPwd"></md-icon>  
    60.                         <input type="password" class="form-control" name="uPwd" ng-model="uPwd" md-maxlength="10" required autofocus />  
    61.                         <div ng-messages="userForm.uPwd.$error">  
    62.                             <div ng-message="required">Password is required !</div>  
    63.                             <div ng-message="md-maxlength">Maximum 10 characters allowed !</div>  
    64.                         </div>  
    65.                     </md-input-container>  
    66.   
    67.                     <md-input-container class="md-icon-float md-block" flex-gt-sm>  
    68.                         <md-button class="md-raised md-primary" ng-click="SaveUser();" ng-disabled="!(fName && lName && uEmail && uName && uPwd)">  
    69.                             <md-tooltip>  
    70.                                 Save  
    71.                             </md-tooltip>  
    72.                             Save  
    73.                         </md-button>  
    74.                         <md-button class="md-raised md-primary">  
    75.                             <md-tooltip>  
    76.                                 Sign in  
    77.                             </md-tooltip>  
    78.                             Sign in</md-button>  
    79.   
    80.                     </md-input-container>  
    81.                 </div>  
    82.             </form>  
    83.         </md-content>  
    84.     </div>  
    85. </body>  
    86.   
    87. </html>  
  • In the code shown above, every tag is prefixed with md and .md is a prefixed for Angular material design.

  • Let's start with each and every tag .

  • md-content is a tag, in which all the code resides. It is given with a class, that is defined in the Angular css file with certain designs.

  • md-toolbar is used to design a toolbar on the upper side of the page.

  • md-input-container is a Container for input like in the bootstrap, it contains class for display icon and other css effects of label, which is defined inside this.

  • md-icon is used to display the icon before the control and we have to give path of the icon in md-svg-src attribute of this tag.

  • ng-messages is used to display the error message for the control on violation of validation rules.

  • ng-message is used inside the ng-messages tag to display multiple messages.

  • Both of these are used with div tags.

  • Inside the ng-messages atribute, we have to give the model name of the field with check of an error.

  • Inside the ng-message attribute, the type of validation is declared. For ex.-- we declare, what is required in an input tag. This is used with ng-message to display the required message.

Create Scripts

  • Create Module.js file in the content folder of Solution Explorer.

  • Write the code, given below, in the file.
    1. var app = angular.module("myApp", ['ngMaterial','ngMessages']);  
  • Here, in the code, we register the app with Angular.

  • ngMaterial directive is used to register with Angular material library and ngMessages are used to display the messages.

  • Create Controller.js file in the same folder.

    Start writing code
    1. app.controller("controll", function($scope, myService)   
    2.  {  
    3.   
    4.   
    5.     $scope.SaveUser = function()  
    6.     {  
    7.   
    8.         var User =  
    9.         {  
    10.             FName: $scope.fName,  
    11.             LName: $scope.lName,  
    12.             Email: $scope.uEmail,  
    13.             Password: $scope.uPwd,  
    14.             UserName: $scope.uName  
    15.         };  
    16.   
    17.         var response = myService.AddUser(User);  
    18.         response.then(function(data)  
    19.         {  
    20.             if (data.data == "1")   
    21.             {  
    22.   
    23.                 clearFields();  
    24.                 alert("User Created !");  
    25.                 window.location.href = "/Register/Login";  
    26.             } else if (data.data == "-1")  
    27.             {  
    28.   
    29.                 alert("user already present !");  
    30.             } else  
    31.             {  
    32.   
    33.                 clearFields();  
    34.                 alert("Invalid data entered !");  
    35.             }  
    36.         });  
    37.     }  
    38.   
    39.     function clearFields()   
    40.   {  
    41.         $scope.fName = "";  
    42.         $scope.lName = "";  
    43.         $scope.uEmail = "";  
    44.         $scope.uPwd = "";  
    45.         $scope.uName = "";  
    46.         $scope.userForm.$setPristine();  
    47.     }  
    48. });  
  • Here, in the Controller Register, the Controller with name controll helps to declare $scope and service.

  • Create SaveUser() function to get the data from the page and send it to the service for further processing.

  • AddUser() function from the service is called by passing data to the function.

  • clearFields() function is used to clear the textboxes.

  • Create Service.js file in the same folder.

    Write the code as given below
    1. app.service("myService", function($http)   
    2. {  
    3.   
    4.     this.AddUser = function(User)   
    5.     {  
    6.         var response = $http  
    7.         ({  
    8.             method: "post",  
    9.             url: "/Register/AddUser",  
    10.             data: JSON.stringify(User),  
    11.             dataType: "json"  
    12.         });  
    13.         return response;  
    14.     };  
    15. });  
  • Here, myService is the name with which the service is registered.

  • AddUser function calls the AddUser method from the Server.

  • Pass the correct URL in the URL Parameter.

Write Server code

  • Go to the Register controller, add method AddUser with string as a return type.

    See the code, shown below:
    1. public string AddUser(Login1 usr)  
    2. {  
    3.     if (usr != null)   
    4.     {  
    5.         if (CheckUser(usr.UserName) == false)  
    6.         {  
    7.             using(SahilEntities context = new SahilEntities())  
    8.             {  
    9.                 Login1 createUser = new Login1();  
    10.                 createUser.UserName = usr.UserName;  
    11.                 createUser.Fname = usr.Fname;  
    12.                 createUser.Lname = usr.Lname;  
    13.                 createUser.Email = usr.Email;  
    14.                 createUser.DateTimeCreated = DateTime.Now;  
    15.                 createUser.Password = usr.Password;  
    16.                 context.Logins1.Add(createUser);  
    17.                 context.SaveChanges();  
    18.             }  
    19.             return "1";  
    20.         } else  
    21.         {  
    22.             return "-1";  
    23.         }  
    24.     } else   
    25.     {  
    26.         return "0";  
    27.     }  
    28. }  
    29.   
    30. public bool CheckUser(string user)  
    31. {  
    32.     bool Exists = false;  
    33.     using(SahilEntities context = new SahilEntities())  
    34.     {  
    35.         var uName = context.Logins1.Where(x => x.UserName == user).ToList();  
    36.         if (uName.Count != 0)  
    37.         {  
    38.             Exists = true;  
    39.         }  
    40.     }  
    41.     return Exists;  
    42. }  
  • There are 2 methods; one is AddUser that returns response on the basis of execution.

  • Other is CheckUser that checks if the user already exists or not.

  • If a user already exists, an error displays, otherwise a user is created.

Including scripts in the view

  • Go to the Register.cshtml and include the Angular module, controller and service file in the head section of the page.

  • @section scripts are used to include the script files.
    1. <head>  
    2.     <title>Register</title>  
    3.   
    4.     @section scripts  
    5.     {  
    6.   
    7.     <script src="~/Content/Module.js"></script>  
    8.     <script src="~/Content/Service.js"></script>  
    9.     <script src="~/Content/Controller.js"></script>  
    10.     }  
    11.   
    12. </head>  
  • mOpen the VS and create your Website with Angular.JS and give new attractive look with the Angular material.

Refrence articles


Similar Articles