Various Ways Of Form Submission In ASP.NET MVC - Part One

There are various types of techniques to submit a form in ASP.NET MVC. This is a series of 4 articles where you will learn various ways of form submission while working in ASP.NET MVC.
 
This article will increase your knowledge not only for Form Submission but also about the basic terminology of ASP.NET MVC Forms.
 

Flow of article

 
In this article, you will learn the following concepts.
  • What is Form Submit?
  • How many ways to submit the Form?
  • Short Notes on various ways of Form Submission.
  • What is @Html.BeginForm?
  • Syntax of @Html.BeginForm?
  • Explanation of various overloaded method of Html.BeginForm.
    • What is RouteValues?
    • What is HtmlAttributes?
    • What is FormMethod?
  • Task
  • Step by Step Implementation of @Html.BeginForm
    (We will do a POST with @Html.BeginForm)
  • Fast Recap.

What is Form Submit (Submission)?

 
The user fills in the form/page and sends the entered details to the server. In the end, we want information; and the user details should be saved on the server.
 

How many ways are there to submit a Form in ASP.NET MVC

 
Following are the ways to submit the form.
  • @Html.BeginForm with hard-code Action.
  • @Ajax.BeginForm with hard-code Action.
  • HTML Input Submit Button using FormAction, FormMethod attributes.
  • Using jQuery set form Action property.
  • Using jQuery AJAX with FormData.
  • Using jQuery AJAX with serializeFormJSON.

Short Notes

 
@Html.BeginForm
 
BeginForm is an extension method of @HtmlHelper class and used for creating, rendering the form tag in HTML.
 
For more detail visit this link.
 
@Ajax.BeginForm
 
BeginForm is an extension method of @AjaxHelper classes and used for creating, rendering the form tag in HTML. @Ajax.BeginForm Helper method submits the form asynchronously using JavaScript.
 
For more detail visit the link.
 
HTML Submit Button using FormAction, FormMehod
 
This FormAction attribute is new in HTML5 using INPUT type “submit”. FormMethod attribute is where we can define the method of submission “POST” or “GET”.
 
For more detail visit this link.
 
Using jQuery set form Action property
 
We can change action property using jQuery and submit the form on the desired action.
 
For more detail visit this link.
 
Using jQuery AJAX with FormData
 
We can submit the Form using jQuery Ajax with FormData. It's a very simple and fast way to submit the form. FormData is used to create an object and pass the form data. This method or way is not good for more fields forms because we have to assign manually the value of form control to FormData object and property.
 
For more detail visit this link.
 
Using jQuery AJAX with serializeFormJSON
 
Using serializeFormJSON will auto pick the value and generate the object that we can get in the POST action method.
 
What is @Html.BeginForm?
 
BeginForm is @Html helper method is used to render FormTag as well as to post data from view (Form Data ) to controller.
 
@Html.BeginForm reduced our work -- you have to just specify your ACTION, CONTROLLER and TYPE OF METHOD.
 
For using this System.Web.Mvc namespace and System.Web.Mvc.dll file are required. By default, in all MVC projects, System.Web.Mvc namespace is already used. @Html helper method is derived from System.Web.Mvc.
 
Various Ways Of Form Submit In ASP.NET MVC
 
In the above image, you can see HTMLHELPER derived from System.Web.Mvc.
 
Syntax of @Html.BeginForm?
 
@Html.BeginForm()
 
There are a total of 13 overloaded ways to use and implement @Html.BeginForm.
 
In most projects, I used the following overloaded way.
  • @Html.BeginForm(“ActionMethod”,”CotrollerName”)
  • @Html.BeginForm(“ActionMethod”,”CotrollerName”,”FormMethod”)
  • @Html.BeginForm(“ActionMethod”,”CotrollerName”,”RouteValues”,”FormMethod”)
  • @Html.BeginForm(“ActionMethod”,”CotrollerName”,”FormMethod”,”HtmlAttributes”)
How does  @Html.BeginForm work?
 
@Html.BeginForm posts the form to the server.
 
Type1
 
@using @Html.BeginForm()
{
}
 
Above goes to same action method name but on the POST side.
 
Type2
 
@Html.BeginForm(“ActionMethod”,”CotrollerName”,”FormMethod”) :
 
This example form is called “ActionMethod” of “ControllerName” with specific “FormMethod”.
 
E.g.
@Html.BeginForm(“detail”,”EmployeeController”,FormMethod.Post)
 
What is RouteValues?
 
Which data travel along with ActionMethod and Controller.
E.g.
http://www.maonjbkalla.weebly.com/courses
 
(In above URL, you can see there are no route values)
 
E.g.
http://www.maonjbkalla.weebly.com/courses/1
 
(In above url you can see 1 is routevalues)
 
Routevalues accepted by actionmethod.
 
What is HtmlAttributes?
 
We can add HtmlAttributes in @Html.BeginForm. HTML attribute like ID, CLASS, STYLE etc.
 
Syntax
@Html.BeginForm( action, controller, FormMethod, htmlAttributes )
 
E.g
@Html.BeginForm( "employeelist", "employee", FormMethod.Post, new { id=”formid” })
 
What is FormMethod?
 
FormMethod is a command which executes form as POST or GET. FormMethod made HTTP request either in GET or POST form.
 
E.g
@Html.BeginForm( "Login", "Home", FormMethod.Post, new { id=”formname” })
 
Task
 
We have to create the following screen and send entered data to the server and store into a database table.
 
Various Ways Of Form Submit In ASP.NET MVC
 
We will be do the following to complete the task,
  1. Create Table called tblFriends.
  2. Create Asp.Net MVC Project.
  3. Create Code First Entity Framework dbContext classes.
  4. Create Model FriendModel.
  5. Create an ActionMethod called “FriendDetail” inside HomeController.
  6. Create view called “FriendDetail”

Step by Step Implementation of @Html.BeginForm

 
Table Structure 
  1. CREATE TABLE [dbo].[tblFriends](  
  2.     [FriendID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [FriendName] [varchar](100) NULL,  
  4.     [CompanyName] [varchar](100) NULL,  
  5.     [Email] [varchar](200) NULL,  
  6. PRIMARY KEY CLUSTERED   
  7. (  
  8.     [FriendID] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY]  
Insert Query Sample Records
  1. insert tblFriends (FriendName,CompanyName,Email) Values('Suhana Kalla','Kalla Infotech','[email protected]')  
  2.   
  3. insert tblFriends (FriendName,CompanyName,Email) Values('Ashish Kalla','AK Infotech','[email protected]')  
  4.   
  5. insert tblFriends (FriendName,CompanyName,Email) Values('Manoj Kalla','Durga Consultancy','[email protected]')  
  6.   
  7. insert tblFriends (FriendName,CompanyName,Email) Values('Ganesh Vyas','Vyas Infoline','[email protected]')  
  8.   
  9. insert tblFriends (FriendName,CompanyName,Email) Values('Rajesh Garg','Garg Infosys','[email protected]')  
Start Visual Studio 2015 or 2017, I am using Visual Studio Community 2015.
 
Select File --> New -->Project
 
Various Ways Of Form Submit In ASP.NET MVC
 
Image No.01 -- (create a new project called “MVC-BeginForm”)
 
As you can see the new project created is named “MVC-BeginForm”.
 
Various Ways Of Form Submit In ASP.NET MVC
 
Image No.01 -- (create a new project called “MVC-BeginForm”)
 
First Open Web.Config set Database connection string as follows,
  1. <connectionStrings>  
  2.     <add name="MBKTest" connectionString="Data Source=(localdb)\MBK;Initial Catalog=MBKTest;Integrated Security=True;" providerName="System.Data.SqlClient" />  
  3.   </connectionStrings>  
Now switch to Solution Explorer by pressing [CTRL+R] or click on VIEW --->Solution Explorer.
 
Insert Package of Entity Framework
 
Various Ways Of Form Submit In ASP.NET MVC
 
Various Ways Of Form Submit In ASP.NET MVC
 
Now again right click on project
 
Various Ways Of Form Submit In ASP.NET MVC
 
Various Ways Of Form Submit In ASP.NET MVC
 
File Name : MBKTestContext and click on ADD button.
  1. using MVC_BeginForm.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6. using System.Web;  
  7.   
  8. namespace MVC_BeginForm  
  9. {  
  10.     public class MBKTestContext : DbContext  
  11.     {  
  12.         public MBKTestContext(): base("MBKTest")  
  13.         {  
  14.   
  15.         }  
  16.         public DbSet<tblFriend> Friends { getset; }  
  17.     }  
  18. }  
Added namespace System.Data.Entity, MVC_BeginForm.Models because DbContext derived from System.Data.Entity and tblFriend derived from MVC_BeginForm.Models
  1. using System.Data.Entity;  
  2. using MVC_BeginForm.Models;  
Now click on MODELS folder and right click select ADD ---> Class called tblFriend
 
Various Ways Of Form Submit In ASP.NET MVC
 
Code Of tblFriend.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.ComponentModel.DataAnnotations;  
  6.   
  7. namespace MVC_BeginForm.Models  
  8. {  
  9.     public class tblFriend  
  10.     {  
  11. [Key]  
  12.         public int FriendID { getset; }   
  13.         public string FriendName { getset; }  
  14.         public string CompanyName { getset; }  
  15.         public string Email { getset; }  
  16.     }  
  17. }  
Now switch back to MBKContext.cs
 
Add the following namespace MVC_BeginForm.Models
  1. using MVC_BeginForm.Models;  
Double click on Controller Folder then select double click on HomeController.
 
Add following code into file.
  1. [HttpGet] 
  2.         public ActionResult FriendDetail()  
  3.         {  
  4.   
  5.             return View();  
  6.         }  
  7.   
  8.         [HttpPost]  
  9.         public ActionResult FriendDetail(tblFriend _friend)  
  10.         {  
  11.   
  12.             return View();  
  13.         }  
Now build your project by right click on Project name MVC_BeginForm
 
Now switch back to HomeController’s FriendDetail method right click and select ADD VIEW option
 
Various Ways Of Form Submit In ASP.NET MVC 
 
Various Ways Of Form Submit In ASP.NET MVC
 
You can see in VIEWS--->HOME--->FriendDetail.cshtml file has been created.
 
Various Ways Of Form Submit In ASP.NET MVC
 
Now switch back to HomeController again and add the following namespace,
 
Various Ways Of Form Submit In ASP.NET MVC
 
Now, check your database’s table for more details.
 
You can see Record No.6 is added successfully.
 
Various Ways Of Form Submit In ASP.NET MVC
 

FAST RECAP AND CODES

 
Here are all important files name and codes:
  1. Web.Config
    Connection String updated,
    1. <connectionStrings>  
    2.     <add name="MBKTest" connectionString="Data Source=(localdb)\MBK;Initial Catalog=MBKTest;Integrated Security=True;" providerName="System.Data.SqlClient" />  
    3.   </connectionStrings>  
  1. tblFriend.cs
    Inside the model folder, we had created a class file and created a property as same as mentioned in table tblFriends.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.ComponentModel.DataAnnotations;  
    4. using System.Linq;  
    5. using System.Web;  
    6.   
    7. namespace MVC_BeginForm.Models  
    8. {  
    9.     public class tblFriend  
    10.     {  
    11.         [Key]  
    12.         public int FriendID { getset; }  
    13.         public string FriendName { getset; }  
    14.         public string CompanyName { getset; }  
    15.         public string Email { getset; }  
    16.     }  
    17. }  
  1. FriendDetail.cshtml
    1. @model MVC_BeginForm.Models.tblFriend  
    2.   
    3. @{  
    4.     ViewBag.Title = "FriendDetail";  
    5.     Layout = "~/Views/Shared/_Layout.cshtml";  
    6. }  
    7.   
    8. <h2>FriendDetail</h2>  
    9.   
    10.   
    11. @using (Html.BeginForm())   
    12. {  
    13.     @Html.AntiForgeryToken()  
    14.       
    15.     <div class="form-horizontal">  
    16.         <h4>tblFriend</h4>  
    17.         <hr />  
    18.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
    19.   
    20.         <div class="form-group">  
    21.             @Html.LabelFor(model => model.FriendName, htmlAttributes: new { @class = "control-label col-md-2" })  
    22.             <div class="col-md-10">  
    23.                 @Html.EditorFor(model => model.FriendName, new { htmlAttributes = new { @class = "form-control" } })  
    24.                 @Html.ValidationMessageFor(model => model.FriendName, ""new { @class = "text-danger" })  
    25.             </div>  
    26.         </div>  
    27.   
    28.         <div class="form-group">  
    29.             @Html.LabelFor(model => model.CompanyName, htmlAttributes: new { @class = "control-label col-md-2" })  
    30.             <div class="col-md-10">  
    31.                 @Html.EditorFor(model => model.CompanyName, new { htmlAttributes = new { @class = "form-control" } })  
    32.                 @Html.ValidationMessageFor(model => model.CompanyName, ""new { @class = "text-danger" })  
    33.             </div>  
    34.         </div>  
    35.   
    36.         <div class="form-group">  
    37.             @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })  
    38.             <div class="col-md-10">  
    39.                 @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })  
    40.                 @Html.ValidationMessageFor(model => model.Email, ""new { @class = "text-danger" })  
    41.             </div>  
    42.         </div>  
    43.   
    44.         <div class="form-group">  
    45.             <div class="col-md-offset-2 col-md-10">  
    46.                 <input type="submit" value="Create" class="btn btn-default" />  
    47.             </div>  
    48.         </div>  
    49.     </div>  
    50. }  
    51.   
    52. <div>  
    53.     @Html.ActionLink("Back to List""Index")  
    54. </div>  
    55.   
    56. @section Scripts {  
    57.     @Scripts.Render("~/bundles/jqueryval")  
    58. }  
  1. HomeController.cs
    Default Controller file where we had created ActionMethods called
    • FriendDetail that is HTTPGET method.
    • FriendDetail that is HTTPPOST method where we had written code of saving a new record in tblFriends table of MBKTest database.
      1. [HttpGet]  
      2.       public ActionResult FriendDetail()  
      3.       {  
      4.   
      5.           return View();  
      6.       }  
      7.   
      8.       [HttpPost]  
      9.       public ActionResult FriendDetail(tblFriend _friend)  
      10.       {  
      11.           MBKTestContext db = new MBKTestContext();  
      12.           db.Friends.Add(_friend);  
      13.           db.SaveChanges();  
      14.           return View();  
      15.    }  
  1. MBKTestContext.cs
    Context file which interacts with the database.
    1. using MVC_BeginForm.Models;  
    2. using System;  
    3. using System.Collections.Generic;  
    4. using System.Data.Entity;  
    5. using System.Linq;  
    6. using System.Web;  
    7.   
    8. namespace MVC_BeginForm  
    9. {  
    10.     public class MBKTestContext : DbContext  
    11.     {  
    12.         public MBKTestContext(): base("MBKTest")  
    13.         {  
    14.   
    15.         }  
    16.   
    17.         public DbSet<tblFriend> Friends { getset; }  
    18.   
    19.     }  
    20. }  
Happy Coding. . .


Similar Articles