Introduction
In this post, I would like to explain Part 6 - How to create simple registration form with validation using angularjs and asp.net mvc4.This is our 6th Post about AngularJS. Here I have explained a little about AngularJS and What we will learn in this section part by part.
In the previous example we have seen Part 3 - How to create a login page using AngularJS in MVC4 application
Here in this post I explained how can we create simple registration form with validation using angularjs and asp.net mvc4. As registration form is a very common form for Internet application, so I would like to create a simple registration form here to demonstrate validation and Save data to the database.
Steps :
Step-1: Create a table into the database.
Here I have modified existing created table named User (created at Part 3 of this series). I have added 2 new fields here Email ID and Gender.Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
Step-2: Update Entity Data Model.
Go to Solution Explorer > Open your Entity Data Model (here "MyModel.edmx") > Right Click On Blank area for Get Context Menu > Update Model From Database... > A popup window will come (Entity Data Model Wizard) > Select Tables > Finish.Step-3: Add new action into your controller (here in the Data Controller) for Save Data to the Database.
Here I have added "Register" Action into "DataController". Please write this following code//Save Simple Registration Form [HttpPost] public JsonResult Register(User u) { string message = ""; //Here we will save data to the database if (ModelState.IsValid) { using (MyDatabaseEntities dc = new MyDatabaseEntities()) { //check username available var user = dc.Users.Where(a => a.Username.Equals(u.Username)).FirstOrDefault(); if (user == null) { //Save here dc.Users.Add(u); dc.SaveChanges(); message = "Success"; } else { message = "Username not available!"; } } } else { message = "Failed!"; } return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; }
Step-4: Add Validation attribute to the model for Server side validation.
namespace MVCWithAngularJs { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public partial class User { public int UserID { get; set; } [Required(ErrorMessage="Username required", AllowEmptyStrings=false)] public string Username { get; set; } [Required(ErrorMessage = "Password required", AllowEmptyStrings = false)] public string Password { get; set; } [Required(ErrorMessage = "Fullname required", AllowEmptyStrings = false)] public string FullName { get; set; } [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage="Email ID not valid")] public string EmailID { get; set; } [Required(ErrorMessage = "Gender required", AllowEmptyStrings = false)] public string Gender { get; set; } } }
Step-5: Add a new js File for add a new AngularJS controller and a Factory
Go to Solution Explorer > Right Click on folder (where you want to saved your AngularJS controller files, here I have created a folder named "AngularController" under Scripts Folder) > Add > Select Javascript file > Enter name > Add.Write following code in this file.
angular.module('MyApp') //extending angular module from First Part .controller('Part6Controller', function ($scope, RegistrationService) { //explained about controller in Part 2 //Default Variable $scope.submitText = "Save"; $scope.submitted = false; $scope.message = ''; $scope.isFormValid = false; $scope.User = { Username : '', Password: '', FullName: '', EmailID: '', Gender:'' }; //Check form Validation // here f1 is our form name $scope.$watch('f1.$valid', function (newValue) { $scope.isFormValid = newValue; }); //Save Data $scope.SaveData = function (data) { if ($scope.submitText == 'Save') { $scope.submitted = true; $scope.message = ''; if ($scope.isFormValid) { $scope.submitText = 'Please Wait...'; $scope.User = data; RegistrationService.SaveFormData($scope.User).then(function (d) { alert(d); if (d == 'Success') { //have to clear form here ClearForm(); } $scope.submitText = "Save"; }); } else { $scope.message = 'Please fill required fields value'; } } } //Clear Form (reset) function ClearForm() { $scope.User = {}; $scope.f1.$setPristine(); //here f1 our form name $scope.submitted = false; } }) .factory('RegistrationService', function ($http, $q) { //explained about factory in Part 2 //here $q is a angularjs service with help us to run asynchronous function and return result when processing done var fac = {}; fac.SaveFormData = function (data) { var defer = $q.defer(); $http({ url: '/Data/Register', method: 'POST', data: JSON.stringify(data), headers: {'content-type' : 'application/json'} }).success(function (d) { // Success callback defer.resolve(d); }).error(function (e) { //Failed Callback alert('Error!'); defer.reject(e); }); return defer.promise; } return fac; });
We will see more about $q later.
Step-6: Add new action into your controller (here in the HomeController) for Get the View for implement registration form.
Here I have added "Part6" Action into "Home" Controller. Please write this following codepublic ActionResult Part6() // Implement Cascade dropdownlist { return View(); }
Step-7: Add view for the Action & design.
Right Click on Action Method (here right click on Part6 action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.Complete View
@{ ViewBag.Title = "Part6"; } <style> input{ padding:5px; border:1px solid #A5A5A5; } input.ng-dirty.ng-invalid { border:1px solid red; background-color:rgb(255, 244, 244); } .error { color:red; } </style> <h2>Simple Registration Form</h2> <div ng-controller="Part6Controller"> <form novalidate name="f1" ng-submit="SaveData(User)"> <div style="color:red">{{message}}</div> <table> <tr> <td>Full Name : </td> <td> <input type="text" ng-model="User.FullName" name="uFullName" ng-class="submitted?'ng-dirty':''" required autofocus /> <span class="error" ng-show="(f1.uFullName.$dirty || submitted) && f1.uFullName.$error.required" >Fullname required!</span> <!-- here (f1.uFullName.$dirty || submitted) means if submit button clicked or it is dirty --> </td> </tr> <tr> <td>Email ID : </td> <td> <input type="email" ng-model="User.EmailID" name="uEmailID" ng-class="submitted?'ng-dirty':''" /> <!-- Not required--> <span class="error" ng-show="(f1.uEmailID.$dirty || submitted) && f1.uEmailID.$error.email">Email ID not valid!</span> @* here f1.uEmailID.$error.email will check is provided email id valid or not *@ </td> </tr> <tr> <td>Username : </td> <td> <input type="text" ng-model="User.Username" name="uUsername" ng-class="submitted?'ng-dirty':''" required /> <span class="error" ng-show="(f1.uUsername.$dirty || submitted) && f1.uUsername.$error.required">Username required!</span> </td> </tr> <tr> <td>Password : </td> <td> <input type="password" ng-model="User.Password" name="uPassword" ng-class="submitted?'ng-dirty':''" required /> <span class="error" ng-show="(f1.uPassword.$dirty || submitted) && f1.uPassword.$error.required">Password required!</span> </td> </tr> <tr> <td> Gender : </td> <td> <input type="radio" ng-model="User.Gender" name="uGender" value="Male" required /> Male <input type="radio" ng-model="User.Gender" name="uGender" value="Female" required /> Female <span class="error" ng-show="(f1.uGender.$dirty || submitted) && f1.uGender.$error.required">Gender required!</span> </td> </tr> <tr> <td></td> <td> <input type="submit" value="{{submitText}}" /> </td> </tr> </table> </form> </div> @section Scripts{ <script src="~/Scripts/AngularController/Part6Controller.js"></script> }