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
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.
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.
Step 4
We are developing a registration page which is going to look like this. It contains form validations as well.
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.
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.
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule, ReactiveFormsModule } from '@angular/forms';
- import { AppComponent } from './app.component';
-
- @NgModule({
- imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
- declarations: [ AppComponent ],
- bootstrap: [ AppComponent ]
- })
- 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
- import {Component } from '@angular/core';
- import { FormBuilder , FormGroup, Validators } from '@angular/forms';
-
- @Component({
- selector: 'app-registration',
- templateUrl: '../Scripts/App/UI/registration.component.html',
- styles: ['p {font-family: Lato;} ']
- })
- export class RegistrationComponent {
- userForm: any;
-
- constructor(private formBuilder: FormBuilder) {
- this.CreateForm();
-
- }
- CreateForm() {
- this.userForm = this.formBuilder.group({
- 'name': ['', Validators.required],
- 'email': ['', [Validators.required]],
- 'password': ['', [Validators.required]],
- 'confirmPassword': ['', [Validators.required]],
-
-
- }
-
- saveUser(): void {
- if (this.userForm.dirty && this.userForm.valid) {
-
- }
- }
- }
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
- <div class="container">
- <h2>Employee Registration</h2>
- <form class="form-horizontal" [formGroup]="userForm" (submit)="saveUser()">
- <div class="form-group">
- <label class="control-label col-sm-2" for="name">Name:</label>
- <div class="col-sm-10">
- <input class="form-control" formControlName="name" id="name" />
- </div>
- </div>
- <div class="form-group">
- <label class="control-label col-sm-2" for="email">Email:</label>
- <div class="col-sm-10">
- <input class="form-control" formControlName="email" id="email" />
-
- </div>
- </div>
- <div class="form-group">
- <label class="control-label col-sm-2" for="password">Password:</label>
- <div class="col-sm-10">
- <input class="form-control" type="password" formControlName="password" id="password" />
-
- </div>
- </div>
- <div class="form-group">
- <label class="control-label col-sm-2" for="confirmPassword">Confirm Password:</label>
- <div class="col-sm-10">
- <input class="form-control" type="password" formControlName="confirmPassword" id="confirmPassword" />
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-offset-2 col-sm-10">
- <button type="submit" [disabled]="!userForm.valid" class="btn btn-success">Submit</button>
- </div>
- </div>
- </form>
- </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.
- 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.
- declarations: [
- RegistrationComponent
- ],
- bootstrap: [
- RegistrationComponent
- ]
Views/index.cshtml
- <app-registration>Loading...</app-registration>
Step 10
Save and run the browser which will give the following output with required validation.
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.
- [HttpPost]
- public ActionResult Register(Table register)
- {
- try
- {
- _db.Tables.Add(register);
- _db.SaveChanges();
- }
- catch (Exception ex)
- {
- throw;
- }
- return Json("OK", JsonRequestBehavior.AllowGet);
- }
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
- import { Injectable } from '@angular/core';
- import { Http, Response, Headers, RequestOptions } from '@angular/http';
- import { Observable } from 'rxjs/Observable';
- import 'rxjs/add/operator/map';
- import 'rxjs/add/operator/do';
- import 'rxjs/add/operator/catch';
-
- @Injectable()
- export class UserService {
- constructor(private _http: Http) { }
-
- InsertUser(url: string, model: any): Observable<any> {
- let body = JSON.stringify(model);
- let headers = new Headers({ 'Content-Type': 'application/json' });
- let options = new RequestOptions({ headers: headers });
- return this._http.post(url, body, options)
- .map((response: Response) => <any>response.json())
- .catch(this.handleError);
-
- }
-
- private handleError(Error: Response) {
- console.error(Error);
- return Observable.throw(Error.json().error || 'Server error');
- }
- }
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
- export interface User
- {
- name: string;
- email: string;
- password: string;
- confirmPassword: string;
- createddate: string
- }
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.
- import { User } from '../model/user.interface';
- import { UserService } from '../services/user.service';
The complete code of registration.component.ts will look like below.
registration.component.ts
- import { Component } from '@angular/core';
- import { FormBuilder, FormGroup, Validators } from '@angular/forms';
- import { User } from '../model/user.interface';
- import { UserService } from '../services/user.service';
- import { DatePipe } from '@angular/common';
-
- @Component({
- selector: 'app-registration',
- templateUrl: '../Scripts/App/UI/registration.component.html',
- styles: ['p {font-family: Lato;} '],
- providers: [UserService],
- })
- export class RegistrationComponent {
- userForm: any;
- user: User;
- toDay = new Date();
-
- constructor(private formBuilder: FormBuilder, private _userService: UserService, private _datepipe: DatePipe) {
- this.CreateForm();
-
- }
- CreateForm() {
- this.userForm = this.formBuilder.group({
- 'name': ['', Validators.required],
- 'email': ['', [Validators.required]],
- 'password': ['', [Validators.required]],
- 'confirmPassword': ['', [Validators.required]]
- });
-
- }
-
- saveUser(): void {
- if (this.userForm.dirty && this.userForm.valid) {
-
- this.user = {
- name: this.userForm.value.name,
- email: this.userForm.value.email,
- password: this.userForm.value.password,
- confirmPassword: this.userForm.value.confirmPassword,
- createddate: this._datepipe.transform(this.toDay, "yyyy-MM-dd")
-
- }
- console.log(this.user);
- this._userService.InsertUser("/Home/Register", this.user).subscribe((data) => {
- if (data == "ok") {
- console.log('success');
- }
- });
- }
- }
- }
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.