Asp.Net MVC jQuery AJAX Form Submit using Serialize Form Data into a Model

Introduction

 
This article helps beginner and advanced developers get VIEW form data into controller side with help of JQUERY AJAX. In this walk through you will see controller side received data on click of SUBMIT button. 
 
Those who are new will enjoy learning how to make the empty template of Asp.Net MVC ready. 
 
You will learn following things in this article
  • How to add jquery in project
  • Where NuGet stores installed Packages details  
  • Jquery Ajax Form Submit using Serializing Form Data into a Model
 
image1
 
Create a project called “AspNetMvcJqueryAjaxSerializeForm” 
 
image2 
 
Click Ok to proceed
 
image3 
 
By default view after “AspNetMvcJqueryAjaxSerializeForm”project created.
 
In empty project template visual studio will not give any controller , model and view. All three folders called CONTROLLERS, MODELS and VIEWS are blank only Web.Config file exists inside VIEWS folder.
  

How to add jquery in project?

 
Now we are going to add Jquery into project with help of NUGET. 
 
Right Click on Project title inside SOLULTION EXPLORER. 
 
 
 
Select option called Manage NuGet Packages. . . 
 
Follow the simple steps as given in image  
 
image5 
 
STEPS
  1. Select browse to do search for jquery.
  2. Type “Jquery” to search.
  3. Single click on Jquery 
  4. You can select your desired version.
  5. Click on Install 
After selecting dialog box, in output window you will get this message: 
 
image6 
 
image7 
 
In the above you can see jquery installed successfully. You can even see Package.config file. 
 
image8 
 

Where NuGet store installed Packages details?

 
Package.config file maintains the list of NuGet packages. 
 
Now we are going create new CONTROLLER called FriendController. 
 
Right click on CONTROLLERS folder select ADD --> Controller 
 
image9 
 
image10
 
image11
 
In FriendController you can see following ACTIONRESULT method  is created
  1. Index.
  2. Details
  3. Create -- HTTP GET
  4. Create - HTTP POST
  5. Edit -- HTTP GET
  6. Edit - HTTP POST
  7. Delete - HTTP GET
  8. Delete - HTTP POST
Now we create model called “FriendModel”
 
Right click on Models folder.
 
Select ADD ---> Class -->FriendModel  (give name FRIENDMODEL) 
 
image12 
 
image13 
 
image14 
  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Web;   
  5.   
  6. namespace AspNetMvcJqueryAjaxSerializeForm.Models   
  7. {   
  8.     public class FriendModel   
  9.     {   
  10.         public string FriendName { get; set; }   
  11.         public string Phone { get; set; }   
  12.         public string State { get; set; }   
  13.     }   
  14. }  
Build Project by Right clicking on Solution-Explorer. 
 
image15 
 
At left side bottom you can see “Build Succeeded”.
 
Again Switch back to FriendController controller.
 
Right click on Create ActionResult. 
 
image16 
 
image17 
 
Now you can see in Shared folder ---> _Layout.cshtml created.
 
Double click on _Layout.cshtml file:
 
At bottom Visual Studio added Jquery link  that is wrong because 
 
We have added Jquery 3.4.1 .
  1. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
image18
 
Copy this link and paste at head section, we had added latest version of jquery and you can cross check in SCRIPTS folder the jquery version.
 
Change according current version you had downloaded from NuGet. 
 
Move the this line  <script src="~/Scripts/jquery-3.4.1.min.js"></script>
 
Code at top following location:  
 
image19 
 
To check if jquery has started working or not you just put the following code at the bottom of Create.cshtml.
  1. <script>  
  2.     $(document).ready(function(){  
  3.         console.log("ready!");  
  4.         alert("ready");  
  5.     });  
  6. </script>  
Press F5 and execute project you will get following screen: 
 
image20 
 
You can see tin he above screenshot the ready alert box has appeared. 
 
Now switch back to FriendController 
 

Add namespace at top of the file

 
Using AspNetMvcJqueryAjaxSerializeForm.Models;
 
We added namespace because our model reside.
 
Now select Create HTTP Post method rename as AddFriend do following changes: 
 
image21 
 
  1.   // POST: Friend/AddFriend  
  2. [HttpPost]  
  3. public ActionResult AddFriend(FriendModel fm)  
  4. {  
  5.           //Write your database insert code / activities  
  6.             return RedirectToAction("create");  
Now switch back to Create.cshtml file and update code. 
  1. @{   
  2.     ViewBag.Title = "Create";   
  3. }   
  4.   
  5. <h2>Create</h2>   
  6. <form id="friendform">   
  7.     <table>   
  8.         <tr>   
  9.             <td>Friend Name</td>   
  10.             <td><input id="txtFriendName" name="FriendName" type="text" /></td>   
  11.         </tr>   
  12.         <tr>   
  13.             <td>Phone</td>   
  14.             <td><input id="txtPhone" name="Phone" type="text" /></td>   
  15.         </tr>   
  16.         <tr>   
  17.             <td>State</td>   
  18.             <td><input id="txtState" name="State" type="text" /></td>   
  19.         </tr>  
  20.     </table>   
  21.  <input id="btnsubmit" type="button" value="Submit"/>   
  22. </form>   
  23.   
  24. <script>   
  25.     $(document).ready(function(){   
  26.         console.log("ready!");   
  27.         alert("ready");   
  28.     });   
  29. </script>  
     
Now Press <F5> key to view output. 
 
image22 
 
Our next step is to insert Jquery Ajax Form Submit with Serializing because our article title is  Asp.Net MVC jQuery AJAX Form Submit using Serialize Form Data into Model.
 
Switch back to CREATE.CSHTML file to insert AJAX code. 
  1. <script>   
  2.     $(document).ready(function () {   
  3.         $("#btnsubmit").click(function (e) {   
  4.             //Serialize the form datas.   
  5.             var valdata = $("#friendform").serialize();   
  6.             //to get alert popup   
  7.             alert(valdata);   
  8.             $.ajax({   
  9.                 url: "/Friend/AddFriend",   
  10.                 type: "POST",   
  11.                 dataType: 'json',   
  12.                 contentType: 'application/x-www-form-urlencoded; charset=UTF-8',   
  13.                 data: valdata   
  14.             });   
  15.         });   
  16.     });   
  17. </script>  
     
Now switch to CONTROLLER to mark BREAKPOINT or DEBUGGER 
 
image23 
 
image24 
You can see in the above form where we enter data. On clicking on SUBMIT button this data we should get in controller side ADDFRIEND method. 
 
image25 
 
As I clicked on SUBMIT button alert popup appeared. 
 
image26 
 
You can see values are separated with & symbol.
 
 
image27 
 
In the above screen you can see we received data from view.
 
To recap the article, we have taken following steps: 
  1. Created Empty Asp.Net MVC project
  2. Installed Jquery from NuGet
  3. Created Controller called “FriendController”
  4. Created View “Create”
  5. Created ActionMethod “AddFriend”
Putting all the important code at one place: 
 
FriendController.cs Code
  1. using AspNetMvcJqueryAjaxSerializeForm.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace AspNetMvcJqueryAjaxSerializeForm.Controllers  
  9. {  
  10.     public class FriendController : Controller  
  11.     {  
  12.         // GET: Friend/Create  
  13.         public ActionResult Create()  
  14.         {  
  15.             return View();  
  16.         }  
  17.         // POST: Friend/AddFriend  
  18.         [HttpPost]  
  19.         public ActionResult AddFriend(FriendModel fm)  
  20.         {  
  21.             //Write your database insert code / activities  
  22.             return RedirectToAction("create");  
  23.         }  
  24.     }  
  25. }  
     
FriendModel.cs Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace AspNetMvcJqueryAjaxSerializeForm.Models  
  7. {  
  8.     public class FriendModel  
  9.     {  
  10.         public string FriendName { getset; }  
  11.         public string Phone { getset; }  
  12.         public string State { getset; }  
  13.     }  
  14. }  
     
Create.cshtml Code
  1. @{  
  2.     ViewBag.Title = "Create";  
  3. }  
  4.   
  5.  <h2>Create</h2>  
  6. <form id="friendform">  
  7.     <table>  
  8.         <tr>  
  9.             <td>Friend Name</td>  
  10.             <td><input id="txtFriendName" name="FriendName" type="text" /></td>  
  11.         </tr>  
  12.         <tr>  
  13.             <td>Phone</td>  
  14.             <td><input id="txtPhone" name="Phone" type="text" /></td>  
  15.         </tr>  
  16.         <tr>  
  17.             <td>State</td>  
  18.             <td><input id="txtState" name="State" type="text" /></td>  
  19.         </tr>  
  20.     </table>  
  21.     <input id="btnsubmit" type="button" value="Submit" />  
  22. </form>  
  23. <script>  
  24.     $(document).ready(function () {  
  25.         $("#btnsubmit").click(function (e) {  
  26.             //Serialize the form datas.  
  27.             var valdata = $("#friendform").serialize();  
  28.             //to get alert popup  
  29.             alert(valdata);  
  30.             $.ajax({  
  31.                 url: "/Friend/AddFriend",  
  32.                 type: "POST",  
  33.                 dataType: 'json',  
  34.                 contentType: 'application/x-www-form-urlencoded; charset=UTF-8',  
  35.                 data: valdata  
  36.             });  
  37.         });  
  38.     });  
  39. </script>   
     
_Layout.cshtml Code
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title - My ASP.NET Application</title>  
  7.     <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />  
  8.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />  
  9.     <script src="~/Scripts/modernizr-2.6.2.js"></script>  
  10.     <script src="~/Scripts/jquery-3.4.1.min.js"></script>  
  11. </head>  
  12. <body>  
  13.     <div class="navbar navbar-inverse navbar-fixed-top">  
  14.         <div class="container">  
  15.             <div class="navbar-header">  
  16.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  17.                     <span class="icon-bar"></span>  
  18.                     <span class="icon-bar"></span>  
  19.                     <span class="icon-bar"></span>  
  20.                 </button>  
  21.                 @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })  
  22.             </div>  
  23.             <div class="navbar-collapse collapse">  
  24.                 <ul class="nav navbar-nav">  
  25.                 </ul>  
  26.             </div>  
  27.         </div>  
  28.     </div>  
  29.     <div class="container body-content">  
  30.         @RenderBody()  
  31.         <hr />  
  32.         <footer>  
  33.             <p>© @DateTime.Now.Year - My ASP.NET Application</p>  
  34.         </footer>  
  35.     </div>  
  36.     <script src="~/Scripts/bootstrap.min.js"></script>  
  37. </body>  
  38. </html>  
     
Happy Coding. 


Similar Articles