Sunday, 19 July 2015

How to Insert Data Into Database Table Using jQuery in ASP.Net MVC4

Introduction
This article explains how to insert data into a SQL Server database using jQuery using a post method in ASP.NET MVC 4.

Step 1: Create new project

Go to "File" -> "New" -> "Project..." then Select ASP.NET MVC4 web application then enter the Application Name then click OK then select Internet Application then select View Engine Razor then click OK.
Step 2: Add a database and create a table in it.

Go to Solution Explorer then right-click on the App_Data folder then click Add > New item then select SQL Server Database under Data then enter the database name then click Add.
  1. CREATE TABLE [dbo].[tblUserInfo] (  
  2.    [Id] INT IDENTITY (1, 1) NOT NULL,  
  3.    [UserName]    VARCHAR (50) NULL,  
  4.    [UserContact] VARCHAR (50) NULL,  
  5.    PRIMARY KEY CLUSTERED ([Id] ASC)  
  6. );  
Step 3: Add entity data model

Go to Solution Explorer then right-click on the project name in the Solution Explorer then click Add > New item then select ADO.Net Entity Data Model under Data then enter the model name then click Add.

The Entity Data Model Wizard will open as a popup window then select Generate from database then click Next.

Choose your data connection then select your database then click Next then select Tables then enter the Model namespace then click Finish.

Step 4: Apply validation on model
Open your model and add validation.
  1. namespace MvcAppInsertUsingJquery  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.     using System.ComponentModel.DataAnnotations;  
  6.       
  7.     public partial class tblUserInfo  
  8.     {  
  9.         public int Id { getset; }  
  10.         [Required(ErrorMessage = "Contact Name required!", AllowEmptyStrings = false)]  
  11.         public string UserName { getset; }  
  12.         [Required(ErrorMessage = "Contact No required!", AllowEmptyStrings = false)]  
  13.         public string UserContact { getset; }  
  14.     }  
  15. }  
Step 5: Add a new controller

Go to Solution Explorer then right-click on the Controllers folder in the Solution Explorer then click Add > Controller then enter the Controller name then select Templete "empty MVC Controller".

Step 6: Add a new action into your controller to insert the data. Here I added a "Save" Action into the "Ajax" Controller. Please write the following code:
  1. public ActionResult Save()  
  2. {  
  3.     return View();  
  4. }  
Step 7: Add view for the action
Right-click on the Action Method then click Add View then enter View Name then select View Engine then check "Create a strong-typed view" then select your model class then click Add.
  1. @model MvcAppInsertUsingJquery.tblUserInfo  
  2.   
  3. @{  
  4.     ViewBag.Title = "Save";  
  5. }  
  6.   
  7. <style>  
  8.     .success {  
  9.         border:solid 1px #0d6d00;  
  10.         width:300px;  
  11.         padding:5px;  
  12.         background-color:#d7ffda;  
  13.     }  
  14.     .failed {   
  15.         border:solid 1px red;  
  16.         width:300px;  
  17.         padding:5px;  
  18.         background-color:#ffe5e5;  
  19.     }  
  20. </style>  
  21.    
  22. <h2 style="font-size:12pt; font-weight:bold;">Ajax Save - Contact Info</h2>  
  23. @using (Html.BeginForm()) {   
  24.     @Html.ValidationSummary(true);  
  25.         <fieldset style="background-color:#ffffff">  
  26.         <legend>Contact Info</legend>  
  27.         <div style="padding:20px;">  
  28.             <div class="editor-label">  
  29.             Contact Name  
  30.         </div>  
  31.         <div class="editor-field">  
  32.             @Html.EditorFor(model => model.UserName)  
  33.             @Html.ValidationMessageFor(model => model.UserName)  
  34.         </div>  
  35.    
  36.         <div class="editor-label">  
  37.             Contact No  
  38.         </div>  
  39.         <div class="editor-field">  
  40.             @Html.EditorFor(model => model.UserContact)  
  41.             @Html.ValidationMessageFor(model => model.UserContact)  
  42.         </div>  
  43.    
  44.         <p>  
  45.             <input type="button" value="Save" id="AjaxPost"/>  
  46.         </p>  
  47.         <div id="content">  
  48.    
  49.         </div>  
  50.             </div>  
  51.     </fieldset>  
  52. }  
  53. <div>  
  54.     @Html.ActionLink("Back to List""Index")  
  55. </div>  
  56. @section Scripts{  
  57.     @Scripts.Render("~/bundles/jqueryval")  
  58.     <script>  
  59.         $(document).ready(function(){  
  60.             $("#AjaxPost").click(function(){  
  61.                 $("#content").html("<b>Please Wait...</b>");  
  62.    
  63.                 var dataObject = {  
  64.                     UserName: $("#UserName").val(),  
  65.                     UserContact: $("#UserContact").val()  
  66.                 };  
  67.                 $.ajax({  
  68.                     url: "@Url.Action("Save","InsertData")",  
  69.                     type: "POST",  
  70.                     data: dataObject,  
  71.                     dataType: "json",  
  72.                     success: function (data) {  
  73.                         if (data.toString() == "Successfully Saved!") {  
  74.                             $("#UserName").val('');  
  75.                             $("#UserContact").val('');  
  76.                             $("#content").html("<div class='success'>"+data+"</div>");  
  77.                         }  
  78.                         else {  
  79.                             $("#content").html("<div class='failed'>" + data + "</div>");  
  80.                         }  
  81.                     },  
  82.                     error: function () {  
  83.                         $("#content").html("<div class='failed'>Error! Please try again</div>");  
  84.                     }  
  85.                 });  
  86.             })  
  87.         })  
  88.     </script>  
  89. }  
Step 8: Add another action into the controller for inserting the data into the server. Here I added a "Save" Action into the "Ajax" Controller for a POST Action.
  1. [HttpPost]  
  2. public ActionResult Save(tblUserInfo userinfo)  
  3. {  
  4.     string message = "";  
  5.     if(ModelState.IsValid)  
  6.     {  
  7.        try  
  8.        {  
  9.            using(AjaxInsertDBEntities aid=new AjaxInsertDBEntities())  
  10.            {  
  11.                aid.tblUserInfoes.Add(userinfo);  
  12.                aid.SaveChanges();  
  13.                message = "Successfully Saved!";  
  14.            }  
  15.        }  
  16.        catch (Exception ex) { message = "Error! Please try again."; }  
  17.     }  
  18.     else  
  19.     {  
  20.         message = "Please provide required fields value.";  
  21.     }  
  22.     if (Request.IsAjaxRequest())  
  23.     {  
  24.         return new JsonResult { Data = message, JsonRequestBehavior = RequestBehavior.AllowGet };  
  25.     }  
  26.     else  
  27.     {  
  28.         ViewBag.Message = message;  
  29.         return View(userinfo);  
  30.     }  
  31. }  
Step 9: Run the application.

No comments:

Post a Comment