Insert record in database using angular js

In this blog I will explain about how we can save data in SQL database using Angular JS.
In this example i have written a web method which is available in .cs file.

So lets start by create a web application in VS2015.
On ASPX Page:

Link this script in head section of page:

<script src=”../js/angular.min.js”></script>


Write this code in your body tag:


<div ng-app=”myApp” ng-controller=”blogCtrl” > 
                            
                            <h2>Enter your data here</h2>
                               <strong>Blog title*</strong><br />
                                <input type=”text” name=”title” id=”txtBlogTitle” placeholder=”write a suitable title.” ng-model=”blogTitle” />                           
                            <strong>Blog Post*</strong><br />
                                <textarea id=”txtBlogPost” placeholder=”Write your social view” ng-model=”blogPost”></textarea>
                            <input id=”btnPost” type=”button” value=”Post” ng-click=”Save()” />
                        </div>


Write this code before closing of body tag:


<script>
        var app = angular.module(“myApp”, []);
        app.controller(“blogCtrl”, function ($scope, $http) {
            $scope.Save = function () {
                $.ajax({
                    type: “POST”,
                    url: “post-blog.aspx/insertblog”,
                    data: “{‘blogTitle’:'” + $scope.blogTitle + “‘,’blogPost’:'” + $scope.blogPost + “‘ }”,
                    contentType: “application/json; charset=utf-8”,
                    dataType: “json”,
                    success: function (msg) {
                        alert(msg.d);
                    },
                    error: function (msg) {
                        alert(msg.d);
                    }
                });
            };
        });
    </script>

Code Behind

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string insertblog(string blogTitle, string blogPost)
    {
        
        //Write code to save data in sql, using stored procedure and parameters
        return “Record Inserted Successfully”;

Leave a Comment

RSS
YouTube
YouTube
Instagram