How to insert data in database using Angularjs in Asp.net MVC application
Introduction:
In my previous article, I have explained How to Get and Display Table Data from Database using AngularJs in Asp.net MVC. Today in this article, I will explain How to insert data in the database using Angularjs in Asp.net MVC application. In this example, I have used Ado.Net for database operation and Angular2.
In this example, we will insert a record into MS SQL database using AngularJs.
Ok, let’s start to insert data into database using AngularJs in asp.net MVC
Follow these steps in order to implement “Insert data into database using AngularJs in Asp.net MVC”
Step1: Create New Project.
Go to File > New > Project > Web > Asp.net MVC web project > Enter Application Name > Select your project location > click to add button > It will show new dialog window for select template > here we will select empty project > then click to OK
Step2: Create a table and Stored procedure in the database.
In this example, I have used fallowing table for insert record in the database.
CREATE TABLE [dbo].[tbl_registration] (
[Sr_no] INT IDENTITY (1, 1) NOT NULL,
[Email] NVARCHAR (100) NULL,
[Password] NVARCHAR (MAX) NULL,
[Name] VARCHAR (MAX) NULL,
[Address] NVARCHAR (MAX) NULL,
[City] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_tbl_registration] PRIMARY KEY CLUSTERED ([Sr_no] ASC)
);
Now create stored procedure for insert all record into database table
Create proc Sp_register
@Email NVARCHAR (100) ,
@Password NVARCHAR (MAX) ,
@Name VARCHAR (MAX) ,
@Address NVARCHAR (MAX) ,
@City NVARCHAR (MAX)
as
begin
insert into tbl_registration values(@Email,@Password,@Name , @Address,@City
)
end
Run above script in MS SQL Server and click to execute button
Step3: Add Connection string in web.config file
Here I have added connection string in ‘web.config’ file under Configuration section as follows
<connectionStrings>
<add name="con" connectionString="Data Source=.;Initial Catalog=test;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Step4: Create a controller.
Go to Solutions Explorer > right click on controller folder > Add Controller > Enter Controller name > Select template “empty MVC Controller ” > Add.
Here I have created a controller “HomeController”
Now we will add a view for Index action where we will insert a record into the database table.
Step5: Add model class for table
Go to Model folder >> Right click on model >> Add new class
Here I have added class as ‘registration.cs’. It contain fallowing code
public class registration
{
public int Sr_no { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
}
Step6: Create Database Access layer.
Here in this example, I have used Ado.net as database operation so we need to create a class for all database operations. Here I have created ‘db.cs’ class.
Go to Solutions Explorer > right click on project solution> Add New Folder > Enter Folder name (Here I rename it as ‘database_access_layer’) > right click on folder > Add new class.
Now add the fallowing method into Database access class that insert all record into the database table.
public class db
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
public void Add_register(registration rs)
{
SqlCommand com = new SqlCommand("Sp_register", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Email",rs.Email);
com.Parameters.AddWithValue("@Password",rs.Password);
com.Parameters.AddWithValue("@Name",rs.Name);
com.Parameters.AddWithValue("@Address",rs.Address);
com.Parameters.AddWithValue("@City",rs.City);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
}
Entire db.cs class will be as fallows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using AngularInsert.Models;
namespace AngularInsert.Database_Access_Layer
{
public class db
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
public void Add_register(registration rs)
{
SqlCommand com = new SqlCommand("Sp_register", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Email",rs.Email);
com.Parameters.AddWithValue("@Password",rs.Password);
com.Parameters.AddWithValue("@Name",rs.Name);
com.Parameters.AddWithValue("@Address",rs.Address);
com.Parameters.AddWithValue("@City",rs.City);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
}
}
Step7: Add new action method in a controller for insert data into the database.
Here I have created ‘Register’ action method in HomeController, that look like as follows
[HttpPost]
public JsonResult Register(registration rs)
{
string res = string.Empty;
try
{
dblayer.Add_register(rs);
res = "Successfully Inserted...!";
}
catch (Exception)
{
res = "Failed";
}
return Json(res, JsonRequestBehavior.AllowGet);
}
Entire HomeController look like as follows:
using AngularInsert.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AngularInsert.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
Database_Access_Layer.db dblayer = new Database_Access_Layer.db();
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Register(registration rs)
{
string res = string.Empty;
try
{
dblayer.Add_register(rs);
res = "Successfully Inserted...!";
}
catch (Exception)
{
res = "Failed";
}
return Json(res, JsonRequestBehavior.AllowGet);
}
}
}
Step8: Add New JS file for AngularJS Controller and AngularJS library file
Go to Solution Explorer > Right Click on the folder (where you want to save your AngularJS controller JS files, here I have created a folder named "AngularController" under Script Folder) > Add > Select Javascript file > Enter name > Add.
We write fallowing code into this file
var app = angular.module('homeapp', []);
app.controller('HomeController', function ($scope, $http) {
$scope.btntext = "Save";
$scope.savedata = function () {
$scope.btntext = "Please wait...!";
$http({
method: 'POST',
url: '/Home/Register',
data: $scope.registration
}).success(function () {
$scope.btntext = "Save";
$scope.registration = null;
alert('Data Submitted...!');
}).error(function () {
alert('Failed');
});
}
});
Here I have created an angular controller named as ‘HomeController’ with parameter $http and $scope
$http: $http is an AngularJS service for reading data from remote servers. It makes a request to the server and returns a response.
$Scope: $Scope is the binding part between the HTML (view) and the JavaScript (controller). It is an object with the available properties and methods. $Scope is available for both the view and the controller.
Step9: Add new action into the controller for insert data into the database.
Here I have added ‘Index’ into ‘HomeController’. I have fallowing code.
public ActionResult Index()
{
return View();
}
Step10: Add view for action in controller & design.
Right Click on Index Action Method > Add View > Enter View Name > Select View Engine (Razor) > Add.
It has fallowing code and design
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body ng-app="homeapp">
<div ng-controller="HomeController">
<form>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right">Email</label>
<div class="col-sm-9">
<input type="text" name="title" ng-model="registration.Email" placeholder="Eg. Email" class="col-xs-10 col-sm-8" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right">Passowrd</label>
<div class="col-sm-9">
<input type="password" name="title" ng-model="registration.Password" placeholder="Eg. Company Secretary" class="col-xs-10 col-sm-8" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right">Name</label>
<div class="col-sm-9">
<input type="text" name="title" ng-model="registration.Name" placeholder="Eg. Company Secretary" class="col-xs-10 col-sm-8" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right">Address</label>
<div class="col-sm-9">
<input type="text" name="title" ng-model="registration.Address" placeholder="Eg. Company Secretary" class="col-xs-10 col-sm-8" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right">City</label>
<div class="col-sm-9">
<select class="col-xs-10 col-sm-8" ng-model="registration.City">
<option value="New Delhi">New Delhi</option>
<option value="Noida">Noida</option>
<option value="Ghaziabad">Ghaziabad</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-9">
<input type="button" value="{{btntext}}" ng-click="savedata()" class="btn btn-primary" />
</div>
</div>
</form>
</div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/AngularController/HomeAngular.js"></script>
</body>
</html>
Step 11: Run Application.
We have done all steps, Now It’s time to run the application