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 of 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 methods 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)
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 the @HtmlHelper class and is used for creating and rendering the form tag in HTML.
For more detail visit this link.
@Ajax.BeginForm
BeginForm is an extension method of @AjaxHelper classes and is used for creating and rendering the form tag in HTML. @Ajax.BeginForm The Helper method submits the form asynchronously using JavaScript.
For more detail visit the link.
HTML Submit Button using FormAction, FormMehod
This information attribute is new in HTML5 using INPUT type “submit”. The form method attribute is where we can define the method of submission as “POST” or “GET”.
For more detail visit this link.
Using jQuery set form Action property
We can change the 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 field forms because we have to assign manually the value of form control to the 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 a @Html helper method used to render FormTag as well as to post data from view (Form Data ) to the 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 files are required. By default, in all MVC projects, System.Web.The mvc namespace is already used. @Html helper method is derived from System.Web.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())
{
}
The above goes to the same action method name but on the POST side.
Type2
@Html.BeginForm("ActionMethod", "ControllerName", 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 the above URL, you can see there are no route values)
E.g. http://www.maonjbkalla.weebly.com/courses/1
(In the above URL you can see 1 is the route value)
Route values accepted by action method.
What is HtmlAttributes?
We can add HtmlAttributes in @Html.BeginForm. HTML attributes 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 that executes form as POST or GET. FormMethod made HTTP requests 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 send the entered data to the server and store it in a database table.
We will be doing the following to complete the task
- Create a Table called tblFriends.
- Create Asp.Net MVC Project.
- Create Code First Entity Framework dbContext classes.
- Create Model FriendModel.
- Create an ActionMethod called “FriendDetail” inside HomeController.
- Create a view called “FriendDetail”
Step-by-step implementation of @Html.BeginForm
Table Structure
CREATE TABLE [dbo].[tblFriends](
[FriendID] [int] IDENTITY(1,1) NOT NULL,
NULL,
NULL,
NULL,
PRIMARY KEY CLUSTERED
(
[FriendID] ASC
)
WITH
(
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
)
ON [PRIMARY]
)
ON [PRIMARY]
Insert Query Sample Records
INSERT INTO tblFriends (FriendName, CompanyName, Email)
VALUES ('Suhana Kalla', 'Kalla Infotech', '[email protected]');
INSERT INTO tblFriends (FriendName, CompanyName, Email)
VALUES ('Ashish Kalla', 'AK Infotech', '[email protected]');
INSERT INTO tblFriends (FriendName, CompanyName, Email)
VALUES ('Manoj Kalla', 'Durga Consultancy', '[email protected]');
INSERT INTO tblFriends (FriendName, CompanyName, Email)
VALUES ('Ganesh Vyas', 'Vyas Infoline', '[email protected]');
INSERT INTO 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
Image No.1. (create a new project called “MVC-BeginForm”)
As you can see the new project created is named “MVC-BeginForm”.
Image No.2. (create a new project called “MVC-BeginForm”)
First Open Web.Config set Database connection string as follows.
<connectionStrings>
<add name="MBKTest"
connectionString="Data Source=(localdb)\MBK;Initial Catalog=MBKTest;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Now switch to Solution Explorer by pressing [CTRL+R] or clicking on VIEW --->Solution Explorer.
Insert Package of Entity Framework
Now again right click on the project
File Name: MBKTestContext and click on the ADD button.
using MVC_BeginForm.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MVC_BeginForm
{
public class MBKTestContext : DbContext
{
public MBKTestContext() : base("MBKTest")
{
}
public DbSet<tblFriend> Friends { get; set; }
}
}
Added namespace System.Data.Entity, MVC_BeginForm.Models because DbContext derived from System.Data.Entity and tblFriend derived from MVC_BeginForm.Models
using System.Data.Entity;
using MVC_BeginForm.Models;
Now click on the MODELS folder and right-click select ADD ---> Class called boyfriend
Code Of boyfriend.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MVC_BeginForm.Models
{
public class tblFriend
{
[Key]
public int FriendID { get; set; }
public string FriendName { get; set; }
public string CompanyName { get; set; }
public string Email { get; set; }
}
}
Now switch back to MBKContext.cs
Add the following namespace MVC_BeginForm.Models
using MVC_BeginForm.Models;
Double click on Controller Folder then select double click on HomeController.
Add the following code to the file.
[HttpGet]
public ActionResult FriendDetail()
{
return View();
}
[HttpPost]
public ActionResult FriendDetail(tblFriend _friend)
{
return View();
}
Now build your project by clicking on the Project name MVC_BeginForm
Now switch back to HomeController’s FriendDetail method right click and select the ADD VIEW option
You can see in VIEWS--->HOME--->FriendDetail.cshtml file has been created.
Now switch back to HomeController again and add the following namespace,
Now, check your database’s table for more details.
You can see Record No.6 is added successfully.
FAST RECAP AND CODES
Here are all the important file names and codes
- Web.Config: Connection String updated
<connectionStrings>
<add name="MBKTest"
connectionString="Data Source=(localdb)\MBK;Initial Catalog=MBKTest;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
- tblFriend.cs: Inside the model folder, we created a class file and created a property as same as mentioned in table tblFriends.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MVC_BeginForm.Models
{
public class tblFriend
{
[Key]
public int FriendID { get; set; }
public string FriendName { get; set; }
public string CompanyName { get; set; }
public string Email { get; set; }
}
}
- FriendDetail.cshtml
@model MVC_BeginForm.Models.tblFriend
@{
ViewBag.Title = "FriendDetail";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>FriendDetail</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>tblFriend</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FriendName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FriendName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FriendName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CompanyName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CompanyName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CompanyName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
- HomeController.cs: Default Controller file where we had created ActionMethods called
- MBKTestContext.cs: Context file which interacts with the database.
using MVC_BeginForm.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MVC_BeginForm
{
public class MBKTestContext : DbContext
{
public MBKTestContext() : base("MBKTest")
{
}
public DbSet<tblFriend> Friends { get; set; }
}
}
Happy Coding.