How To Insert Form Data In Multiple Table In Database

In this article we gonna learn about how to insert from data in multiple tables using jquery ajax in asp.net web application.In real time applications it is not a good practice to save all customer data in one table.They save data in multiple tables and link them using relations(using foreign keys).In current article we will see how to do it.Before going to article check related articles in series of asp.net mvc application development.

Inserting form data in multiple table

Topics covered in this article,

  1. Creating database for saving form data in multiple forms.
  2. Preparing model classes(Data transfer objects).
  3. Server side code to save form values into database tables.
  4. How to work with multiple ajax(post) calls in jquery to send data from html page to controller.

Here,to interactive with database i used entity framework ORM tool to perform data base operations.Now let's come to current article,

Steps

  1. Create a asp.net web application in visual studio using empty mvc template.
  2. Create data base for this applications using below sql script code.
    1. CREATE TABLE [dbo].[TUser] (  
    2.     [Id]          INT           IDENTITY (1, 1) NOT NULL,  
    3.     [Name]        NVARCHAR (50) NOT NULL,  
    4.     [Email]       NVARCHAR (50) NOT NULL,  
    5.     [PhoneNumber] BIGINT        NOT NULL,  
    6.     PRIMARY KEY CLUSTERED ([Id] ASC)  
    7. );  
    8. CREATE TABLE [dbo].[TOrders] (  
    9.     [OrderId]     INT           IDENTITY (1, 1) NOT NULL,  
    10.     [ItemName]    NVARCHAR (50) NOT NULL,  
    11.     [PaymentType] NVARCHAR (50) NOT NULL,  
    12.     [Price]       BIGINT        NOT NULL,  
    13.     [Userid]      BIGINT        NOT NULL,  
    14.     PRIMARY KEY CLUSTERED ([OrderId] ASC)  
    15. );  
    16. CREATE TABLE [dbo].[TAddress] (  
    17.     [AddressId] BIGINT        IDENTITY (1, 1) NOT NULL,  
    18.     [Colony]    NVARCHAR (50) NOT NULL,  
    19.     [State]     NVARCHAR (50) NOT NULL,  
    20.     [Country]   NVARCHAR (50) NOT NULL,  
    21.     [Userid]    BIGINT        NOT NULL,  
    22.     PRIMARY KEY CLUSTERED ([AddressId] ASC)  
    23. );  
  3. Here i created 3 tables TUser,TAddress and TOrders where i am maintaining relationship between three tables using userid.
  4. I created a procedure to save user data and prints the latest saved identity column(userid) of TUser table and saving it as a foreign key in TAddress and TOrders tables.
    1. CREATE PROCEDURE [dbo].[sp_InsertUser]  
    2.  @Name nvarchar(225) = null,  
    3.  @Email nvarchar(225) = null,  
    4.  @PhoneNumber Bigint=0  
    5. AS  
    6. BEGIN  
    7.  INSERT INTO TUser(Name,Email,PhoneNumber) VALUES(@Name,@Email,@PhoneNumber)  
    8.  DECLARE @Id INT  
    9.  SET @Id=@@IDENTITY  
    10.  SELECT @Id AS id  
    11. END  
  5. (Add ADO.NET Entity data model)Right click on Models folder --> Add --> ADO.NET Entity DataModel --> Name it --> Select EF designer from Database from Entity Data Model Wizard --> Select connection string and web.config --> click next --> Choose your database objects and settings(here tables and stored procedure you created) and give name to model namespace--> click finish.

  6. Add a controller with index action method and add view to index action method and replace index view code with below html code.
    1. @{  
    2.     ViewBag.Title = "www.mitechdev.com";  
    3. }  
    4.   
    5. <link href="~/Content/Site.css" rel="stylesheet" />  
    6. <div class="container">  
    7.     <form id="contact" action="" method="post">  
    8.         <h4 class="text-info"><strong>Saving Form data in Multiple Tables in DB</strong></h4>  
    9.         <fieldset>  
    10.             <input placeholder="Your name" id="txtname" type="text" tabindex="1" required autofocus>  
    11.         </fieldset>  
    12.         <fieldset>  
    13.             <input placeholder="Your Email Address" id="txtemail" type="email" tabindex="2" required>  
    14.         </fieldset>  
    15.         <fieldset>  
    16.             <input placeholder="Your Phone Number" id="txtphone" type="tel" tabindex="3" required>  
    17.         </fieldset>  
    18.         <fieldset>  
    19.             <input placeholder="Colony" id="txtcolony" type="text" tabindex="4" required />  
    20.         </fieldset>  
    21.         <fieldset>  
    22.             <input placeholder="State" id="txtstate" type="text" tabindex="4" required />  
    23.         </fieldset>  
    24.         <fieldset>  
    25.             <select id="ddlcountry" required>  
    26.                 <option value="">-select country-</option>  
    27.                 <option value="India">India</option>  
    28.                 <option value="USA">USA</option>  
    29.                 <option value="United Kingdom">United Kingdom</option>  
    30.                 <option value="Canada">Canada</option>  
    31.                 <option value="Jermany">Jermany</option>  
    32.             </select>  
    33.         </fieldset>  
    34.         <fieldset>  
    35.             <input placeholder="ItemName" id="txtitemname" type="text" tabindex="4" required />  
    36.         </fieldset>  
    37.         <fieldset>  
    38.             <select id="ddlpaymentttype">  
    39.                 <option value="">-select-</option>  
    40.                 <option value="Credit Card">Credit Card</option>  
    41.                 <option value="Debit Card">Debit Card</option>  
    42.                 <option value="Net Banking">Net Banking</option>  
    43.                 <option value="Other">Other</option>  
    44.             </select>  
    45.         </fieldset>  
    46.         <fieldset>  
    47.             <input placeholder="Price" id="txtprice" type="text" tabindex="4" required />  
    48.         </fieldset>  
    49.         <fieldset>  
    50.             <button name="submit" type="button" id="contact-submit">Submit</button>  
    51.         </fieldset>  
    52.         <p class="copyright">Designed by <a href="https://mitechdev.com" target="_blank" title="mitechdev.com">Mitechdev.com</a></p>  
    53.     </form>  
    54. </div>  
  7. The form screen look like below with attractive css styles.

    form

  8. Add below script to send data from form to server using ajax.Here,in above form i want to save first 3 fields in TUser table,next 3 fields in TAddress table and final 3 fields in TOrders table.

  9. First i am inserting data in TUser using ajax post method next in TAddress using another post ajax method and TOrders using another ajax method.
    1. $(document).ready(function () {  
    2.         $("#contact-submit").click(function () {  
    3.             var url = "@Url.Action("SaveUser","Home")";  
    4.             debugger;  
    5.             var userdata = {  
    6.                 Name: $.trim($("#txtname").val()),  
    7.                 Email: $.trim($("#txtemail").val()),  
    8.                 PhoneNumber:$.trim($("#txtphone").val())  
    9.             };  
    10.             $.post(url, { UserData: userdata }, function (data) {  
    11.                 debugger;  
    12.                 if (data!=0 && data > 0) {  
    13.                     var url = "@Url.Action("SaveAddress","Home")";  
    14.                     var addressdata = {  
    15.                         Colony: $.trim($("#txtcolony").val()),  
    16.                         State: $.trim($("#txtstate").val()),  
    17.                         Country: $.trim($("#ddlcountry").val()),  
    18.                         Userid:data  
    19.                     };  
    20.                     $.post(url, { AddressData: addressdata }, function (response) {  
    21.                         debugger;  
    22.                         if (response == true) {  
    23.                             var orderdata = {  
    24.                                 ItemName: $.trim($("#txtitemname").val()),  
    25.                                 PaymentType: $.trim($("#ddlpaymentttype").val()),  
    26.                                 Price: $.trim($("#txtprice").val()),  
    27.                                 Userid:response  
    28.                             };  
    29.                             $.post("@Url.Action("SaveOrders", "Home")", { OrdersData: orderdata }, function (result) {  
    30.                                 debugger;  
    31.                                 if (result == true) {  
    32.                                     alert("Form data saved successfully in 3 tables");  
    33.                                     resetForm();  
    34.                                 }  
    35.                             });  
    36.                         }  
    37.                     });  
    38.                 }  
    39.             });  
    40.         });  
    41.     });  
    42.     function resetForm() {  
    43.         $("#txtname").val("");  
    44.         $("#txtemail").val("");  
    45.         $("#txtphone").val("");  
    46.         $("#txtcolony").val("");  
    47.         $("#txtstate").val("");  
    48.         $("#ddlcountry").val("");  
    49.         $("#txtitemname").val("");  
    50.         $("#ddlpaymentttype").val("");  
    51.         $("#txtprice").val("");  
    52.     }  
    Note

    For this application i not performing any client validations.Refer this link to know how to perform jquery validations on form.In above code resetForm() function clears all user input data after saving in database.

  10. Now replace the controller code with below code.
    1. public class HomeController : Controller  
    2.     {  
    3.         public ActionResult Index()  
    4.         {  
    5.             return View();  
    6.         }  
    7.         public JsonResult SaveUser(TUser UserData)  
    8.         {  
    9.             int Userid = 0;  
    10.             try  
    11.             {  
    12.                 if (UserData != null)  
    13.                 {  
    14.                     using (DatabaseEntities db = new DatabaseEntities())  
    15.                     {  
    16.                         //saves the user data and returns userid from procedure.  
    17.                         var id = db.Database.SqlQuery("sp_InsertUser @Name,@Email,@PhoneNumber",  
    18.                             new SqlParameter("Name",UserData.Name),  
    19.                             new SqlParameter("Email",UserData.Email),  
    20.                             new SqlParameter("PhoneNumber",UserData.PhoneNumber)).Single();  
    21.                         Userid = id;  
    22.                     }  
    23.                 }  
    24.             }  
    25.             catch(Exception ex)  
    26.             {  
    27.                 throw ex;  
    28.             }  
    29.             return Json(Userid, JsonRequestBehavior.AllowGet);  
    30.         }  
    31.         //saves Address data TAddress table  
    32.         public JsonResult SaveAddress(TAddress AddressData)  
    33.         {          
    34.             bool result = false;  
    35.             try  
    36.             {  
    37.                 if (AddressData != null)  
    38.                 {  
    39.                     using (DatabaseEntities db = new DatabaseEntities())  
    40.                     {  
    41.                         db.TAddresses.Add(AddressData);  
    42.                         db.SaveChanges();  
    43.                         result = true;  
    44.                     }  
    45.                 }  
    46.             }  
    47.             catch(Exception ex)  
    48.             {  
    49.                 throw ex;  
    50.             }  
    51.             return Json(result, JsonRequestBehavior.AllowGet);  
    52.         }  
    53.         //saves orderdata in TOrders table  
    54.         public JsonResult SaveOrders(TOrder OrdersData)  
    55.         {  
    56.             bool result = false;  
    57.             try  
    58.             {  
    59.                 if (OrdersData != null)  
    60.                 {  
    61.                     using (DatabaseEntities db = new DatabaseEntities())  
    62.                     {  
    63.                         db.TOrders.Add(OrdersData);  
    64.                         db.SaveChanges();  
    65.                         result = true;  
    66.                     }  
    67.                 }  
    68.             }  
    69.             catch(Exception ex)  
    70.             {  
    71.                 throw ex;  
    72.             }  
    73.             return Json(result, JsonRequestBehavior.AllowGet);  
    74.         }  
    75.     }  
  11. After saving all form data into 3 tables in database a response message comes like below.

     response message 

I hope this article will helps you.If you want to see the original source of this post and download source code for this application click on this How To Insert Form Data In Multiple Table In Database.