Go to Solutions Explorer > right click on project solution> Add New Folder > Enter Folder name (Here I rename it as ‘Data’) > right click on folder > Add new class call Data access
Now add the fallowing method into Database access class named Add_Customer that does all the database access related activities.
Step 5 - Create POST method
Create a Post method in the Asp.net Web API Controller Class.
Open the Values Controller, delete the existing method and create the AddCustomer method and call the database access class (db.cs) method as the following,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using InsertdataWebapi.Models;
- namespace InsertdataWebapi.Controllers {
- public class ValuesController: ApiController {
- database_access_layer.db dblayer = new database_access_layer.db();
- [HttpPost]
- public IHttpActionResult AddCustomer([FromBody] customer cs) {
- try {
- if (!ModelState.IsValid) {
- return BadRequest(ModelState);
- }
- dblayer.Add_Customer(cs);
- return Ok("Success");
- } catch (Exception) {
- return Ok("Something went wrong, try later");
- }
- }
- }
- }
Step 6 - Configure Asp.net Web API routing
We need to configure the routing of the incoming request. Let us create WebApiConfig.cs by right-clicking on the App_start folder and creating the following method:
- public static void Register(HttpConfiguration config) {
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {
- id = RouteParameter.Optional
- });
- }
Step 7 - Call Asp.net Web API Controller method
Call Asp.net Web API Controller method from the HTMLpage using JSON.
Now we need to call to Web API Controller method from HTML page. To do this we need to create a JSON method using Jquery. The entire test.html page will be as follows,
- <script type="text/javascript">
- $(function() {
- var PersonalDetails = {
- "SiteCollectionURL": "",
- "SiteName": "",
- "SiteURL": "",
- "URL": "",
- "UserID": "7364",
- "UserName": "prasanan",
- "UserEmail": "",
- "ItemType": "Item",
- "iso365": "false",
- "CreatedBy": "harup",
- "Created": "08-01-2017",
- "ModifiedBy": "Venkata",
- "Modified": "08-01-2017"
- };
- $.ajax({
- type: "POST",
- url: '/api/Analytics/AddSiteDetails',
- data: JSON.stringify(PersonalDetails),
- contentType: "application/json;charset=utf-8",
- success: function(data, status, xhr) {
- alert("The result is : " + data);
- },
- error: function(xhr) {
- alert(xhr.responseText);
- }
- });
- });
- </script>
Step 8 - Run Application/ Host the Application into IIS
We have done all steps, now it’s time to run the application
Database Section
Step 1 - Create a table and Stored Procedure.
Table Creation
- CREATE TABLE [dbo].[webapitable]
- (
- [id] [INT] IDENTITY(1, 1) NOT NULL,
- [sitecollectionurl] [NVARCHAR](max) NOT NULL,
- [sitename] [NVARCHAR](100) NOT NULL,
- [siteurl] [NVARCHAR](max) NOT NULL,
- [url] [NVARCHAR](max) NOT NULL,
- [userid] [NVARCHAR](100) NOT NULL,
- [username] [NVARCHAR](100) NOT NULL,
- [useremail] [NVARCHAR](max) NOT NULL,
- [itemtype] [NVARCHAR](50) NOT NULL,
- [createdby] [NVARCHAR](max) NULL,
- [created] [DATETIME] NULL,
- [modifiedby] [NVARCHAR](max) NULL,
- [modified] [DATETIME] NULL,
- PRIMARY KEY CLUSTERED ( [id] ASC )WITH (pad_index = OFF,
- statistics_norecompute = OFF, ignore_dup_key = OFF, allow_row_locks = on,
- allow_page_locks = on) ON [PRIMARY]
- )
- ON [PRIMARY]
- textimage_on [PRIMARY]
-
- go
Create a stored procedure to insert data into the table as,
- CREATE PROC [dbo].[Analytics_details_add] @SiteCollectionURL NVARCHAR (max),
- @SiteName NVARCHAR (100),
- @SiteURL NVARCHAR (max),
- @URL NVARCHAR(max),
- @UserID NVARCHAR(100),
- @UserName NVARCHAR(100),
- @UserEmail NVARCHAR(max),
- @ItemType NVARCHAR(50),
- @iso365 BIT,
- @CreatedBy NVARCHAR(max),
- @Created DATETIME,
- @ModifiedBy NVARCHAR(max),
- @Modified DATETIME
- AS
- BEGIN
- INSERT INTO [dbo].[siteanalytics]
- (sitecollectionurl,
- sitename,
- siteurl,
- url,
- userid,
- username,
- useremail,
- itemtype,
- iso365,
- createdby,
- created,
- modifiedby,
- modified)
- VALUES ( @SiteCollectionURL,
- @SiteName,
- @SiteURL,
- @URL,
- @UserID,
- @UserName,
- @UserEmail,
- @ItemType,
- @iso365,
- @CreatedBy,
- Getdate(),
- @ModifiedBy,
- Getdate() )
- END
-
- go
Run the above script in the MS SQL Server and click the execute button.