This article explain how to create and consume Web API POST method in ASP.Net MVC.
Table Script
CREATE TABLE [dbo].[Customer]( [CustId] [INT] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](MAX) NULL, [Address] [nvarchar](MAX) NULL, [Mobile] [nvarchar](MAX) NULL, [Email] [nvarchar](MAX) NULL, CONSTRAINT [PK_dbo.Customer] PRIMARY KEY CLUSTERED ( [CustId] 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
Web API Controller
Inside this Action method, the received Customer object is inserted into the Customers table and the updated Customer object with generated Customer Id is returned back to the calling jQuery AJAX function.
public class CustAPIController : ApiController { [Route("api/CustAPI/InsertCustomer")] [HttpPost] public Customer InsertCustomer(Customer _customer) { using (CustomersEntities entities = new CustomersEntities()) { entities.Customers.Add(_customer); entities.SaveChanges(); } return _customer; } }
View
The View consists of two TextBoxes and a Button. The Button has been assigned with a jQuery Click event handler. When the Add button is clicked, the Name and the Country values are fetched from their respective TextBoxes and then passed to the InsertCustomer Action method using jQuery AJAX function. The ID of the Inserted record is displayed using JavaScript Alert Message Box.
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width"/> <title>Index</title> </head> <body> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td style="width: 150px"> Name<br/> <input type="text" id="txtName" style="width:140px"/> </td> <td style="width: 150px"> Country:<br/> <input type="text" id="txtCountry" style="width:140px"/> </td> <td style="width: 200px"> <br/> <input type="button" id="btnAdd" value="Add"/> </td> </tr> </table> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script> <script type="text/javascript"> $("body").on("click", "#btnAdd", function () { var txtName = $("#txtName"); var txtCountry = $("#txtCountry"); var _customer = {}; _customer.Name = txtName.val(); _customer.Country = txtCountry.val(); $.ajax({ type: "POST", url: "/api/CustAPI/InsertCustomer", data: JSON.stringify(_customer), contentType: "application/json; charset=utf-8", dataType: "json", success: function (r) { alert("CustomerMobile: " + r.Mobile.toString());
} }); }); </script> </body> </html>
When we run the application we can easily get the customer information of Mobile.
Post a Comment