Implement Registration Page In Angular With ASP.NET MVC

Since I couldn’t find any resource on implementing the registration form using Angular 2 Forms with ASP.NET MVC., I decided to write an article about it. Hope it will be helpful to you.

Step 1

Set up the ASP.NET MVC project in Visual Studio and name it as ASPNETMVC.NG2
 
Implement Registration Form Using Angular With ASP.NET MVC 

Step 2

Make sure you have set up Node.js and NPM is installed on your machine. Run the following command to install NPM.
 
npm install
 
It will install the node_modules in the project folder, where you had run the npm command.
Implement Registration Form Using Angular With ASP.NET MVC 

Step 3

After installing node_modules, open the NuGet Package Manager and run the following command.

PM> Install-Package Angular2-Template-for-MVC-and-WebAPI -Version 1.0.0 

The above command installs the required TypeScript files with one sample template of Angular 2 in MVC project. Don’t forget to restore the packages from packages.json.

I have created the following folder structure to store the components of Angular 2; you can create your own folder structure.

Implement Registration Form Using Angular With ASP.NET MVC 

Step 4

We are developing a registration page which is going to look like this. It contains form validations as well.
 
Implement Registration Form Using Angular With ASP.NET MVC 

Step 5

Set up the database along with the tables as per your requirement. In this demo, we are using a simple table which stores some basic user details and we are using the DB-first approach.
 
Implement Registration Form Using Angular With ASP.NET MVC 

Step 6

Create a component in App -> Component -> registration.component.ts. This component returns the View for registration page and by default, if you follow the above steps, it will create the default app.module.ts file. There, if you want, you can import the necessary library which will look like below

app.module.ts

This is the default root module of our Angular application and it will be rendered when our application is executed. The module is used to inherit our created components, directives, and services.

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  4. import { AppComponent } from './app.component';  
  5.   
  6. @NgModule({  
  7.   imports:      [ BrowserModule, FormsModule, ReactiveFormsModule ],  
  8.   declarations: [ AppComponent ],  
  9.   bootstrap:    [ AppComponent ]  
  10. })  
  11. export class AppModule { }  

You can see in the above code that app.module.ts will be created by default when we install the Angular template from the NuGet Package Manager. When we create any new component that needs to be registered in declarations in @NgModule, Bootstrap is the place where we can register the first starting component that needs to be loaded for the particular module.

Step 7

Open registration.component.ts which will return the required HTML of the registration page. Here, we are going to use Angular Form Builder and validations using Angular Forms which looks like below, as I have used Validators.Required which is optional. If you use this, you need to add one more component to display the error message in the Div.

registration.component.ts

  1. import {Component } from '@angular/core';  
  2. import { FormBuilder , FormGroup, Validators } from '@angular/forms';  
  3.   
  4. @Component({  
  5.     selector: 'app-registration',  
  6.     templateUrl: '../Scripts/App/UI/registration.component.html',  
  7.     styles: ['p {font-family: Lato;} ']  
  8. })  
  9. export class RegistrationComponent {  
  10.     userForm: any;  
  11.       
  12.     constructor(private formBuilder: FormBuilder) {  
  13.         this.CreateForm();  
  14.   
  15.     }  
  16.     CreateForm() {  
  17.         this.userForm = this.formBuilder.group({  
  18.             'name': ['', Validators.required],  
  19.             'email': ['', [Validators.required]],  
  20.             'password': ['', [Validators.required]],  
  21.             'confirmPassword': ['', [Validators.required]],  
  22.          
  23.         // console.log(this.userForm);  
  24.     }  
  25.   
  26.     saveUser(): void {  
  27.         if (this.userForm.dirty && this.userForm.valid) {  
  28.             // alert(`name' : ${this.userForm.value.name}  'email' : ${this.userForm.value.email}`);              
  29.         }  
  30.     }  
  31. }  

In the above code, we have imported necessary libraries and in @Component, we have declared the selector as 'app-registration' which will be used in the main view to render the component. And create one template in UI folder with a name registration.component.html and given this path in the templateUrl property.

In the constructor, we have injected the FormBuilder module. Using this, we can create the validations for the form that we are going to build. We have used the createForm () method in the constructor which will specify what fields have validation rules.

Step 8

Create a User Interface for rendering the registration form. Open the registration.component.html and paste the below code which will render as a plain HTML.

registration.component.html

  1. <div class="container">  
  2.     <h2>Employee Registration</h2>  
  3.     <form class="form-horizontal" [formGroup]="userForm" (submit)="saveUser()">  
  4.         <div class="form-group">  
  5.             <label class="control-label col-sm-2" for="name">Name:</label>  
  6.             <div class="col-sm-10">  
  7.                 <input class="form-control" formControlName="name" id="name" />  
  8.             </div>  
  9.         </div>  
  10.         <div class="form-group">  
  11.             <label class="control-label col-sm-2" for="email">Email:</label>  
  12.             <div class="col-sm-10">  
  13.                 <input class="form-control" formControlName="email" id="email" />  
  14.                  
  15.             </div>  
  16.         </div>  
  17.         <div class="form-group">  
  18.             <label class="control-label col-sm-2" for="password">Password:</label>  
  19.             <div class="col-sm-10">  
  20.                 <input class="form-control" type="password" formControlName="password" id="password" />  
  21.                   
  22.             </div>  
  23.         </div>  
  24.         <div class="form-group">  
  25.             <label class="control-label col-sm-2" for="confirmPassword">Confirm Password:</label>  
  26.             <div class="col-sm-10">  
  27.                 <input class="form-control" type="password" formControlName="confirmPassword" id="confirmPassword" />  
  28.             </div>  
  29.         </div>  
  30.         <div class="form-group">  
  31.             <div class="col-sm-offset-2 col-sm-10">  
  32.                 <button type="submit" [disabled]="!userForm.valid" class="btn btn-success">Submit</button>  
  33.             </div>  
  34.         </div>  
  35.     </form>  
  36. </div>  

In the above HTML, we have used form group as userForm in the form tag and in controls like textbox, we have used formControlName to give name to the textbox and in Submit button, we have disabled the attribute to disable the button if the form is not valid.

Step 9

Open the app.module.ts file and register the registration component as below.
  1. import {RegistrationComponent} from './component/registration.component';  

Declare the RegistrationComponent in the declarations section and don’t forget to add RegistrationComponent in Bootstrap as well, which will look like below. Change the name to app-registration in Index.cshtml which is present in the Views folder as this will render the component which looks like below.

  1. declarations: [  
  2.         RegistrationComponent  
  3.     ],  
  4. bootstrap: [  
  5.         RegistrationComponent  
  6.     ]  

Views/index.cshtml

  1. <app-registration>Loading...</app-registration>  

Step 10

Save and run the browser which will give the following output with required validation.
 
Implement Registration Form Using Angular With ASP.NET MVC

Step 11

On the button click event of the Submit button, we need to insert the data into the database. As we are using Database-First approach, open the homeController.cs and write one method which will insert the data into the database table.
  1. [HttpPost]  
  2.         public ActionResult Register(Table register)  
  3.         {  
  4.             try  
  5.             {  
  6.                 _db.Tables.Add(register);  
  7.                 _db.SaveChanges();  
  8.             }  
  9.             catch (Exception ex)  
  10.             {  
  11.                 throw;  
  12.             }  
  13.             return Json("OK", JsonRequestBehavior.AllowGet);  
  14.         }  

Step 12

As we have set up the method to insert the data to the database, firstly, we need to post the data on the server-side method. To do that, create a method in Services named User.Service.ts which will make a call to the ASP.NET MVC server-side method and write the below code.

User.service.ts

  1. import { Injectable } from '@angular/core';  
  2. import { Http, Response, Headers, RequestOptions } from '@angular/http';  
  3. import { Observable } from 'rxjs/Observable';  
  4. import 'rxjs/add/operator/map';  
  5. import 'rxjs/add/operator/do';  
  6. import 'rxjs/add/operator/catch';  
  7.   
  8. @Injectable()  
  9. export class UserService {  
  10.     constructor(private _http: Http) { }  
  11.   
  12.     InsertUser(url: string, model: any): Observable<any> {  
  13.         let body = JSON.stringify(model);  
  14.         let headers = new Headers({ 'Content-Type''application/json' });  
  15.         let options = new RequestOptions({ headers: headers });  
  16.         return this._http.post(url, body, options)  
  17.             .map((response: Response) => <any>response.json())  
  18.             .catch(this.handleError);  
  19.   
  20.     }  
  21.   
  22.    private  handleError(Error: Response) {  
  23.         console.error(Error);  
  24.         return Observable.throw(Error.json().error || 'Server error');  
  25.     }  
  26. }  

As you can see in the above code, we have imported the HTTP service library to perform HTTP operations and we have also imported some React.js libraries to handle the exceptions and map the response to the JSON as well.

I have created one method called InsertUser() which accepts the URL and model object as a parameter. This method returns the type observable. This service can be injected into other components and we have also created one method to handle the error using React.js library.

Step 13

Create one interface called user.interface.ts in Models folder in the script. This will hold the user details and pass as an object to call the service in registration.component.

User.interface.ts

  1. export interface User  
  2. {  
  3.     name: string;  
  4.     email: string;  
  5.     password: string;  
  6.     confirmPassword: string;  
  7.     createddate: string  
  8. }  

Step 14

Refer this interface in registration.component.ts to hold the form properties, which looks like below and don’t forget to refer the userService in registration.component in which I have added it earlier.
  1. import { User } from '../model/user.interface';  
  2. import { UserService } from '../services/user.service';  

The complete code of registration.component.ts will look like below.

registration.component.ts

  1. import { Component } from '@angular/core';  
  2. import { FormBuilder, FormGroup, Validators } from '@angular/forms';  
  3. import { User } from '../model/user.interface';  
  4. import { UserService } from '../services/user.service';  
  5. import { DatePipe } from '@angular/common';  
  6.   
  7. @Component({  
  8.     selector: 'app-registration',  
  9.     templateUrl: '../Scripts/App/UI/registration.component.html',  
  10.     styles: ['p {font-family: Lato;} '],  
  11.     providers: [UserService],  
  12. })  
  13. export class RegistrationComponent {  
  14.     userForm: any;  
  15.     user: User;  
  16.     toDay = new Date();  
  17.   
  18.     constructor(private formBuilder: FormBuilder, private _userService: UserService, private _datepipe: DatePipe) {  
  19.         this.CreateForm();  
  20.   
  21.     }  
  22.     CreateForm() {  
  23.         this.userForm = this.formBuilder.group({  
  24.             'name': ['', Validators.required],  
  25.             'email': ['', [Validators.required]],  
  26.             'password': ['', [Validators.required]],  
  27.             'confirmPassword': ['', [Validators.required]]  
  28.         });  
  29.         // console.log(this.userForm);  
  30.     }  
  31.   
  32.     saveUser(): void {  
  33.         if (this.userForm.dirty && this.userForm.valid) {  
  34.             // alert(`name' : ${this.userForm.value.name}  'email' : ${this.userForm.value.email}`);  
  35.             this.user = {  
  36.                 name: this.userForm.value.name,  
  37.                 email: this.userForm.value.email,  
  38.                 password: this.userForm.value.password,  
  39.                 confirmPassword: this.userForm.value.confirmPassword,  
  40.                 createddate: this._datepipe.transform(this.toDay, "yyyy-MM-dd")  
  41.   
  42.             }  
  43.             console.log(this.user);  
  44.             this._userService.InsertUser("/Home/Register"this.user).subscribe((data) => {  
  45.                 if (data == "ok") {  
  46.                     console.log('success');  
  47.                 }  
  48.             });  
  49.         }  
  50.     }  
  51. }  

As you can see in the above code, we have imported the necessary libraries and in saveUser() method, we are filling the interface model. Here, we are calling the InsertUser method from userService. We can pass the correct controller and action method as parameters which will subscribes the result of the server-side method.

Implement Registration Form Using Angular With ASP.NET MVC


Similar Articles