-->

How to insert data into sql server database using jquery with Preventing CSRF Attacks in asp.net MVC 4 Application

How to insert data into sql server databse using jquery with Preventing CSRF Attacks

Introduction

In the previous example we have seen that How to insert data into sql server database using jquery (post method) in asp.net MVC 4 Application. But there was not used AntiForgeryToken.
AntiForgeryToken is used for prevent CSRF (Cross Site Request Forgery) attack. CSRF is a way of hack where hacker exploits the trust of a website on the user.
Here we will see How to insert data into sql server databse using jquery with Preventing CSRF Attacks 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.  
  7. public partial class ContactInfo
  8. {
  9. public int ID { get; set; }
  10. [Required(ErrorMessage="Contact Name required!", AllowEmptyStrings=false)]
  11. public string ContactName { get; set; }
  12. [Required(ErrorMessage="Contact No required!", AllowEmptyStrings=false)]
  13. public string ContactNo { get; set; }
  14. }
  15. }

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. // Here Add validation token with dataObject
  11. dataObject.__RequestVerificationToken = $("input[name=__RequestVerificationToken]").val();
  12. $.ajax({
  13. url: "@Url.Action("Save","Ajax")",
  14. type: "POST",
  15. data: dataObject,
  16. dataType: "json",
  17. success: function (data) {
  18. if (data.toString() == "Successfully Saved!") {
  19. $("#ContactName").val('');
  20. $("#ContactNo").val('');
  21. $("#content").html("<div class='success'>"+data+"</div>");
  22. }
  23. else {
  24. $("#content").html("<div class='failed'>" + data + "</div>");
  25. }
  26. },
  27. error: function () {
  28. $("#content").html("<div class='failed'>Error! Please try again</div>");
  29. }
  30. });
  31.  
  32. });
  33. });
  34. </script>
Complete View
  1. @model MVCAjaxSave.ContactInfo
  2. @{
  3. ViewBag.Title = "Ajax Save - Contact Info";
  4. }
  5.  
  6. <style>
  7. .success {
  8. border:solid 1px rgb(13,109,0);
  9. width:300px;
  10. padding:5px;
  11. background-color:rgb(215,255,218);
  12. }
  13. .failed {
  14.  
  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. @Html.AntiForgeryToken()
  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. // Here Add validation token with dataObject
  73. dataObject.__RequestVerificationToken = $("input[name=__RequestVerificationToken]").val();
  74. $.ajax({
  75. url: "@Url.Action("Save","Ajax")",
  76. type: "POST",
  77. data: dataObject,
  78. dataType: "json",
  79. success: function (data) {
  80. if (data.toString() == "Successfully Saved!") {
  81. $("#ContactName").val('');
  82. $("#ContactNo").val('');
  83. $("#content").html("<div class='success'>"+data+"</div>");
  84. }
  85. else {
  86. $("#content").html("<div class='failed'>" + data + "</div>");
  87. }
  88. },
  89. error: function () {
  90. $("#content").html("<div class='failed'>Error! Please try again</div>");
  91. }
  92. });
  93.  
  94. });
  95. });
  96. </script>
  97. }
  98.  

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

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
  2. How to insert data into sql server databse using jquery (post method) in asp.net MVC 4 Application.
How to insert data into sql server databse using jquery with Preventing CSRF Attacks




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: