-->

Part 6 - How to create simple registration form with validation using angularjs and asp.net mvc4.


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.
In this example, I have used one tables as below


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

  1. //Save Simple Registration Form
  2. [HttpPost]
  3. public JsonResult Register(User u)
  4. {
  5. string message = "";
  6. //Here we will save data to the database
  7. if (ModelState.IsValid)
  8. {
  9. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  10. {
  11. //check username available
  12. var user = dc.Users.Where(a => a.Username.Equals(u.Username)).FirstOrDefault();
  13. if (user == null)
  14. {
  15. //Save here
  16. dc.Users.Add(u);
  17. dc.SaveChanges();
  18. message = "Success";
  19. }
  20. else
  21. {
  22. message = "Username not available!";
  23. }
  24. }
  25. }
  26. else
  27. {
  28. message = "Failed!";
  29. }
  30. return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  31. }

Step-4: Add Validation attribute to the model for Server side validation.


  1. namespace MVCWithAngularJs
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel.DataAnnotations;
  6. public partial class User
  7. {
  8. public int UserID { get; set; }
  9. [Required(ErrorMessage="Username required", AllowEmptyStrings=false)]
  10. public string Username { get; set; }
  11. [Required(ErrorMessage = "Password required", AllowEmptyStrings = false)]
  12. public string Password { get; set; }
  13. [Required(ErrorMessage = "Fullname required", AllowEmptyStrings = false)]
  14. public string FullName { get; set; }
  15. [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")]
  16. public string EmailID { get; set; }
  17. [Required(ErrorMessage = "Gender required", AllowEmptyStrings = false)]
  18. public string Gender { get; set; }
  19. }
  20. }
  21.  

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.

  1. angular.module('MyApp') //extending angular module from First Part
  2. .controller('Part6Controller', function ($scope, RegistrationService) { //explained about controller in Part 2
  3. //Default Variable
  4. $scope.submitText = "Save";
  5. $scope.submitted = false;
  6. $scope.message = '';
  7. $scope.isFormValid = false;
  8. $scope.User = {
  9. Username : '',
  10. Password: '',
  11. FullName: '',
  12. EmailID: '',
  13. Gender:''
  14. };
  15. //Check form Validation // here f1 is our form name
  16. $scope.$watch('f1.$valid', function (newValue) {
  17. $scope.isFormValid = newValue;
  18. });
  19. //Save Data
  20. $scope.SaveData = function (data) {
  21. if ($scope.submitText == 'Save') {
  22. $scope.submitted = true;
  23. $scope.message = '';
  24.  
  25. if ($scope.isFormValid) {
  26. $scope.submitText = 'Please Wait...';
  27. $scope.User = data;
  28. RegistrationService.SaveFormData($scope.User).then(function (d) {
  29. alert(d);
  30. if (d == 'Success') {
  31. //have to clear form here
  32. ClearForm();
  33. }
  34. $scope.submitText = "Save";
  35. });
  36. }
  37. else {
  38. $scope.message = 'Please fill required fields value';
  39. }
  40. }
  41. }
  42. //Clear Form (reset)
  43. function ClearForm() {
  44. $scope.User = {};
  45. $scope.f1.$setPristine(); //here f1 our form name
  46. $scope.submitted = false;
  47. }
  48. })
  49. .factory('RegistrationService', function ($http, $q) { //explained about factory in Part 2
  50. //here $q is a angularjs service with help us to run asynchronous function and return result when processing done
  51. var fac = {};
  52. fac.SaveFormData = function (data) {
  53. var defer = $q.defer();
  54. $http({
  55. url: '/Data/Register',
  56. method: 'POST',
  57. data: JSON.stringify(data),
  58. headers: {'content-type' : 'application/json'}
  59. }).success(function (d) {
  60. // Success callback
  61. defer.resolve(d);
  62. }).error(function (e) {
  63. //Failed Callback
  64. alert('Error!');
  65. defer.reject(e);
  66. });
  67. return defer.promise;
  68. }
  69. return fac;
  70. });
  71.  

Here I have created an angular controller named "Part6Controller" and a Factory named "LocationService" with $http injected service. I have explained a little about AngularJS controller here, about Factory here and about $http here.
here you can see I have used $q, this is a angularjs service with help us to run asynchronous function and return result when processing done.
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 code

  1. public ActionResult Part6() // Implement Cascade dropdownlist
  2. {
  3. return View();
  4. }

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
  1. @{
  2. ViewBag.Title = "Part6";
  3. }
  4. <style>
  5. input{
  6. padding:5px;
  7. border:1px solid #A5A5A5;
  8. }
  9. input.ng-dirty.ng-invalid {
  10. border:1px solid red;
  11. background-color:rgb(255, 244, 244);
  12. }
  13. .error {
  14. color:red;
  15. }
  16. </style>
  17. <h2>Simple Registration Form</h2>
  18. <div ng-controller="Part6Controller">
  19. <form novalidate name="f1" ng-submit="SaveData(User)">
  20. <div style="color:red">{{message}}</div>
  21. <table>
  22. <tr>
  23. <td>Full Name : </td>
  24. <td>
  25. <input type="text" ng-model="User.FullName" name="uFullName" ng-class="submitted?'ng-dirty':''" required autofocus />
  26. <span class="error" ng-show="(f1.uFullName.$dirty || submitted) && f1.uFullName.$error.required" >Fullname required!</span>
  27.  
  28. <!-- here (f1.uFullName.$dirty || submitted) means if submit button clicked or it is dirty -->
  29. </td>
  30. </tr>
  31. <tr>
  32. <td>Email ID : </td>
  33. <td>
  34. <input type="email" ng-model="User.EmailID" name="uEmailID" ng-class="submitted?'ng-dirty':''" /> <!-- Not required-->
  35. <span class="error" ng-show="(f1.uEmailID.$dirty || submitted) && f1.uEmailID.$error.email">Email ID not valid!</span>
  36. @* here f1.uEmailID.$error.email will check is provided email id valid or not *@
  37. </td>
  38. </tr>
  39. <tr>
  40. <td>Username : </td>
  41. <td>
  42. <input type="text" ng-model="User.Username" name="uUsername" ng-class="submitted?'ng-dirty':''" required />
  43. <span class="error" ng-show="(f1.uUsername.$dirty || submitted) && f1.uUsername.$error.required">Username required!</span>
  44. </td>
  45. </tr>
  46. <tr>
  47. <td>Password : </td>
  48. <td>
  49. <input type="password" ng-model="User.Password" name="uPassword" ng-class="submitted?'ng-dirty':''" required />
  50. <span class="error" ng-show="(f1.uPassword.$dirty || submitted) && f1.uPassword.$error.required">Password required!</span>
  51. </td>
  52. </tr>
  53. <tr>
  54. <td> Gender : </td>
  55. <td>
  56. <input type="radio" ng-model="User.Gender" name="uGender" value="Male" required /> Male
  57. <input type="radio" ng-model="User.Gender" name="uGender" value="Female" required /> Female
  58. <span class="error" ng-show="(f1.uGender.$dirty || submitted) && f1.uGender.$error.required">Gender required!</span>
  59. </td>
  60. </tr>
  61. <tr>
  62. <td></td>
  63. <td>
  64. <input type="submit" value="{{submitText}}" />
  65. </td>
  66. </tr>
  67. </table>
  68. </form>
  69. </div>
  70.  
  71. @section Scripts{
  72. <script src="~/Scripts/AngularController/Part6Controller.js"></script>
  73. }
  74.  

Step-8: Run Application.

Download  Live Demo
 


Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.

Related Posts: