-->

How to insert data into sql server databse using jquery (post method) in asp.net MVC 4 Application.

Introduction

In this post, I am explain how to insert data into sql server databse using jquery (post method) in asp.net MVC 4 Application.


Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below


Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Apply Validation On Model.

Open your model and add validation. Please follow below code

  1. namespace MVCAjaxSave
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel.DataAnnotations;
  6. public partial class ContactInfo
  7. {
  8. public int ID { get; set; }
  9. [Required(ErrorMessage="Contact Name required!", AllowEmptyStrings=false)]
  10. public string ContactName { get; set; }
  11. [Required(ErrorMessage="Contact No required!", AllowEmptyStrings=false)]
  12. public string ContactNo { get; set; }
  13. }
  14. }

Step-6: Add a new Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-7: Add new action into your controller for save data.

Here I have added "Save" Action into "Ajax" Controller. Please write this following code

  1. public ActionResult Save()
  2. {
  3. return View();
  4. }

Step-8: Add view for the Action & design.

Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.
[N:B:Please Rebuild solution before add view.]

Step-9: Add jquery code for save data to the server.

Jquery Code
  1. <script>
  2. $(document).ready(function () {
  3. $("#AjaxPost").click(function () {
  4. $("#content").html("<b>Please Wait...</b>");
  5.  
  6. var dataObject = {
  7. ContactName: $("#ContactName").val(),
  8. ContactNo : $("#ContactNo").val()
  9. };
  10.  
  11. $.ajax({
  12. url: "@Url.Action("Save","Ajax")",
  13. type: "POST",
  14. data: dataObject,
  15. dataType: "json",
  16. success: function (data) {
  17. if (data.toString() == "Successfully Saved!") {
  18. $("#ContactName").val('');
  19. $("#ContactNo").val('');
  20. $("#content").html("<div class='success'>"+data+"</div>");
  21. }
  22. else {
  23. $("#content").html("<div class='failed'>" + data + "</div>");
  24. }
  25. },
  26. error: function () {
  27. $("#content").html("<div class='failed'>Error! Please try again</div>");
  28. }
  29. });
  30.  
  31. });
  32. });
  33. </script>
Complete View
  1. @model MVCAjaxSave.ContactInfo
  2.  
  3. @{
  4. ViewBag.Title = "Ajax Save - Contact Info";
  5. }
  6.  
  7. <style>
  8. .success {
  9. border:solid 1px rgb(13,109,0);
  10. width:300px;
  11. padding:5px;
  12. background-color:rgb(215,255,218);
  13. }
  14. .failed {
  15.  
  16. border:solid 1px red;
  17. width:300px;
  18. padding:5px;
  19. background-color:rgb(255,229,229);
  20. }
  21. </style>
  22.  
  23. <h2 style="font-size:12pt; font-weight:bold;">Ajax Save - Contact Info</h2>
  24.  
  25. @using (Html.BeginForm()) {
  26. @Html.ValidationSummary(true)
  27.  
  28. <fieldset style="background-color:#ffffff">
  29. <legend>Contact Info</legend>
  30. <div style="padding:20px;">
  31. <div class="editor-label">
  32. Contact Name
  33. </div>
  34. <div class="editor-field">
  35. @Html.EditorFor(model => model.ContactName)
  36. @Html.ValidationMessageFor(model => model.ContactName)
  37. </div>
  38.  
  39. <div class="editor-label">
  40. Contact No
  41. </div>
  42. <div class="editor-field">
  43. @Html.EditorFor(model => model.ContactNo)
  44. @Html.ValidationMessageFor(model => model.ContactNo)
  45. </div>
  46.  
  47. <p>
  48. <input type="button" value="Save" id="AjaxPost"/>
  49. </p>
  50. <div id="content">
  51.  
  52. </div>
  53. </div>
  54. </fieldset>
  55. }
  56.  
  57. <div>
  58. @Html.ActionLink("Back to List", "Index")
  59. </div>
  60.  
  61. @section Scripts {
  62. @Scripts.Render("~/bundles/jqueryval")
  63. <script>
  64. $(document).ready(function () {
  65. $("#AjaxPost").click(function () {
  66. $("#content").html("<b>Please Wait...</b>");
  67.  
  68. var dataObject = {
  69. ContactName: $("#ContactName").val(),
  70. ContactNo : $("#ContactNo").val()
  71. };
  72.  
  73. $.ajax({
  74. url: "@Url.Action("Save","Ajax")",
  75. type: "POST",
  76. data: dataObject,
  77. dataType: "json",
  78. success: function (data) {
  79. if (data.toString() == "Successfully Saved!") {
  80. $("#ContactName").val('');
  81. $("#ContactNo").val('');
  82. $("#content").html("<div class='success'>"+data+"</div>");
  83. }
  84. else {
  85. $("#content").html("<div class='failed'>" + data + "</div>");
  86. }
  87. },
  88. error: function () {
  89. $("#content").html("<div class='failed'>Error! Please try again</div>");
  90. }
  91. });
  92.  
  93. });
  94. });
  95. </script>
  96. }
  97.  

Step-10: Step-10: Add another action into your controller for Save Data to the server.

Here I have added "Save" Action into "Ajax" Controller for POST Action. Please write this following code

  1. [HttpPost]
  2. public ActionResult Save(ContactInfo CI)
  3. {
  4. string message = "";
  5. if (ModelState.IsValid)
  6. {
  7. try
  8. {
  9. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  10. {
  11. dc.ContactInfoes.Add(CI);
  12. dc.SaveChanges();
  13.  
  14. message = "Successfully Saved!";
  15. }
  16. }
  17. catch (Exception ex)
  18. {
  19. message = "Error! Please try again.";
  20. }
  21. }
  22. else
  23. {
  24. message = "Please provide required fields value.";
  25. }
  26. if (Request.IsAjaxRequest())
  27. {
  28. return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  29. }
  30. else
  31. {
  32. ViewBag.Message = message;
  33. return View(CI);
  34. }
  35. }

Step-11: Run Application.


Download Application     Live Demo


Related Post :
  1. How to insert data into sql server databse using jquery (post method) in asp.net





Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.

Related Posts: