How to create a Registration form using Angular JS in ASP.NET MVC 5 ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Tuesday, 24 May 2016

How to create a Registration form using Angular JS in ASP.NET MVC 5

00:47:00 Posted by raviteja swayampu , , 1 comment
In this tutorial i am going to explain about How to Create simple Registration page using Angular js in MVC 5 application with angular validation.We have learned how to get data from database using angular with help of services.In this tutorial we are using services to save the data in database.
please refer  the below posts for understanding of angular.

Note: I have explained basics of angular js please refer previous posts to understand the basics if you do not know basics. 

The expected outcome for this application is this ...
Registration page using angular js in asp.net mvc5
Registration page using Angular JS

In this application we are using another service $q .Which is an angular service which helps us to run asynchronous function and returns result when the processing is done. 

Step 1: Create a Data table in Database

1.Right click server explorer --> expand Database --> Right click on tables --> Click Add new table.
2.Create a table with  following columns if you want you can add more columns.
3.Here i created following table.

Step 2: Add ADO.NET Entity Data Model

1.Right click on Solution--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.

Step 3: Add New Action Method to save user data in database

1.Add below action method in HomeController to save data which is come from angular controller and saves that in database.
2.Replace the code with following code.
//Registration form saving code
        [HttpPost]
        public JsonResult Register(User u)
        {
            string message = "";          
            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)
                    {                      
                        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 new js file to create angular Controller

1.Before creating angular controller we need to create angular application module.js file.
(function () {
    var myApp = angular.module("myApp",[]);
})();
2.Now create Registration controller --Right click on Scripts folder and add RegistrationController.js
3.Replace the code with below js code.
angular.module('MyApp') 
.controller('RegistationController', function ($scope, RegistrationService) {
    //Default Variable
    $scope.submitText = "Save";
    $scope.submitted = false;
    $scope.message = '';
    $scope.isFormValid = false;
    $scope.User = {
        Username : '',
        Password: '',
        FullName: '',
        EmailID: '',
        Gender:''
    };
    //validates form on client side
    $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 = '';
            }
        }
    }
    //Clear Form 
    function ClearForm() {
        $scope.User = {};
        $scope.f1.$setPristine(); //here f1 is form name
        $scope.submitted = false;
    }
})
.factory('RegistrationService', function ($http, $q) { 
    
    var fac = {};
    fac.SaveFormData = function (data) {
        var defer = $q.defer();
        $http({
            url: '/Home/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;
});

Step 6: Add View to display Registration Form

1.Right click on Index action --> Add View --> add
2.Replace Index.cshtml view code with following code.

@{
    ViewBag.Title = "Registration page using Angular";
}
<style>
    body{
        margin-top:50px;
    }
    input {
        max-width:300px;
    }
    .error {
        color: red;
    }

</style>

<div class="panel panel-info" style="margin-left:30px;margin-right:500px;">
    <div class="panel-heading">
        Sample Registration Form using Angular
    </div>
    <div ng-controller="RegistationController" class="panel-body">
        <form novalidate name="f1" ng-submit="SaveData(User)" class="form-horizontal">
            <div class="form-group">
                <label class="text text-info col-md-offset-2">Full Name : </label>
                <input type="text" ng-model="User.FullName" class="form-control col-md-offset-2" name="uFullName" ng-class="submitted?'ng-dirty':''" required autofocus />
                <span class="error col-md-offset-2" ng-show="(f1.uFullName.$dirty || submitted) && f1.uFullName.$error.required">Fullname required!</span>
            </div>

            <div class="form-group">
                <label class="text text-info col-md-offset-2">Email ID : </label>
                <input type="email" ng-model="User.EmailID" class="form-control col-md-offset-2" name="uEmailID" ng-class="submitted?'ng-dirty':''" />
                <span class="error col-md-offset-2" ng-show="(f1.uEmailID.$dirty || submitted) && f1.uEmailID.$error.required">Email required</span>
                <span class="error col-md-offset-2" ng-show="(f1.uEmailID.$dirty || submitted) && f1.uEmailID.$error.email">Email ID not valid!</span>
            </div>
            <div class="form-group">
                <label class="text text-info col-md-offset-2">Username : </label>
                <input type="text" ng-model="User.Username" class="form-control col-md-offset-2" name="uUsername" ng-class="submitted?'ng-dirty':''" required />
                <span class="error col-md-offset-2" ng-show="(f1.uUsername.$dirty || submitted) && f1.uUsername.$error.required">Username required!</span>
            </div>
            <div class="form-group">
                <label class="text text-info col-md-offset-2">Password : </label>
                <input type="password" ng-model="User.Password" class="form-control col-md-offset-2" name="uPassword" ng-class="submitted?'ng-dirty':''" required />
                <span class="error col-md-offset-2" ng-show="(f1.uPassword.$dirty || submitted) && f1.uPassword.$error.required">Password required!</span>
            </div>
            <div class="form-group">
                <label class="text text-info col-md-offset-2"> Gender : </label>
                <input type="radio" class="col-md-offset-2" ng-model="User.Gender" name="uGender" value="Male" required /> Male
                <input type="radio" class="col-md-offset-2" 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>

            </div>
            <div class="form-group">
                <label></label>
                <input type="submit" class="btn btn-success col-md-offset-2" value="{{submitText}}" />
            </div>
        </form>
    </div>
    <div class="panel-footer">
        Mitechdev application
    </div>
</div> 

@section Scripts{
<script src="~/Scripts/RegistrationController.js"></script>
}

3.Add script reference at the end of Index.cshtml page.
4.For above code we applied Bootstrap styles to beautify form.
5.I used same validation i explained in previous post.

Now run the application and insert some records into form and submit it.
you can see what i  inserted here.

inserted records in table using angular form
inserted records in form


The validation for this form works like below screen shot.

angular form validation in mvc5
Angular form validation
Download source code from here Download

Conclusion:
I hope this tutorial is understandable for every reader.If you recommend any modifications to this site please specify in form of comments to improve the quality of this post.
For daily updates please follow this site through Email or Social networks....


1 comment:

  1. After submitted the data successfully all required errors are shown but i want hide that errors after data submission successfully..

    ReplyDelete