FormCollection In ASP.NET MVC

Introduction

I am going to discuss creating a View to insert a new employee into the database table Employee using FormCollection class, which is available in ASP.NET MVC.

Step 1

Open Visual Studio 2015 or an editor of your choice and create a new project.

Step 2

Choose the web application project and give an appropriate name for your project.
 
FormCollection In ASP.NET MVC

Step 3

Select "empty template", check on MVC checkbox below, and click OK.
 
FormCollection In ASP.NET MVC

Step 4

Right-click on the Models folder and add the database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.
 
FormCollection In ASP.NET MVC

You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add". 

FormCollection In ASP.NET MVC

After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".

FormCollection In ASP.NET MVC

After clicking on "Next", a window will appear. Choose New Connection. Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".

FormCollection In ASP.NET MVC

The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next",

FormCollection In ASP.NET MVC

After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".

FormCollection In ASP.NET MVC

Entity Framework gets added and the respective class gets generated under the Models folder.

FormCollection In ASP.NET MVC

Step 5

Right-click on Controllers folder and add a controller.
 
FormCollection In ASP.NET MVC

A window will appear. Choose MVC5 Controller-Empty and click "Add".

FormCollection In ASP.NET MVC

After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.

FormCollection In ASP.NET MVC

The FormCollection class will automatically receive the posted form values in the controller action method in key/value pairs. Keys & values can be accessed using key names or index.

  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult Create(FormCollection formCollection)  
  4. {  
  5.     if (ModelState.IsValid)  
  6.     {  
  7.         foreach (string key in formCollection.AllKeys)  
  8.         {  
  9.             Response.Write("Key=" + key + " ");  
  10.             Response.Write("Value=" + formCollection[key]);  
  11.             Response.Write("<br/>");  
  12.         }  
  13.     }  
  14.     return View();  
  15. }  

FormCollection In ASP.NET MVC

Complete code for Home Controller

  1. using MvcFormCollection_Demo.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 MvcFormCollection_Demo.Controllers  
  9. {   
  10.     public class HomeController : Controller  
  11.     {  
  12.         private readonly EmployeeContext _dbContext = new EmployeeContext();  
  13.    
  14.         public ActionResult Index()  
  15.         {  
  16.             var employee = _dbContext.Employees.ToList();  
  17.             return View(employee);  
  18.         }  
  19.    
  20.         public ActionResult Create()  
  21.         {  
  22.             return View();  
  23.         }  
  24.    
  25.         [HttpPost]  
  26.         [ValidateAntiForgeryToken]  
  27.         public ActionResult Create(FormCollection formCollection)  
  28.         {  
  29.             if (ModelState.IsValid)  
  30.             {  
  31.                 Employee employee = new Employee();  
  32.                 employee.Name = formCollection["Name"];  
  33.                 employee.Gender = formCollection["Gender"];  
  34.                 employee.Age =Convert.ToInt32(formCollection["Age"]);  
  35.                 employee.Position = formCollection["Position"];  
  36.                 employee.Office = formCollection["Office"];  
  37.                 employee.HireDate = Convert.ToDateTime(formCollection["HireDate"]);  
  38.                 employee.Salary = Convert.ToInt32(formCollection["Salary"]);  
  39.                 _dbContext.Employees.Add(employee);  
  40.                 _dbContext.SaveChanges();  
  41.                 RedirectToAction("Index");  
  42.             }  
  43.             return View();  
  44.         }  
  45.     }  
  46. }

Step 6

Right-click on Index method in HomeController. The "Add View" window will appear with default index name checked (use a Layout page) and click on "Add.
 
FormCollection In ASP.NET MVC

Code for Create View

  1. @model MvcFormCollection_Demo.Models.Employee  
  2.    
  3. @{  
  4.     ViewBag.Title = "Create";  
  5. }  
  6.    
  7. <h3>Create New</h3>  
  8.    
  9. @using (Html.BeginForm())  
  10. {  
  11.     @Html.AntiForgeryToken()  
  12.    
  13.     <div class="form-horizontal">  
  14.         <hr />  
  15.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  16.         <div class="form-group">  
  17.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  18.             <div class="col-md-10">  
  19.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  20.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  21.             </div>  
  22.         </div>  
  23.    
  24.         <div class="form-group">  
  25.             @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })  
  26.             <div class="col-md-10">  
  27.                 @Html.DropDownList("Gender"new List<SelectListItem>  
  28.                 {  
  29.                 new SelectListItem { Text = "Male", Value="Male" },  
  30.                 new SelectListItem { Text = "Female", Value="Female" }  
  31.                 }, "Select Gender"new { @class = "form-control" })  
  32.                 @Html.ValidationMessageFor(model => model.Gender, ""new { @class = "text-danger" })  
  33.             </div>  
  34.         </div>  
  35.    
  36.         <div class="form-group">  
  37.             @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })  
  38.             <div class="col-md-10">  
  39.                 @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })  
  40.                 @Html.ValidationMessageFor(model => model.Age, ""new { @class = "text-danger" })  
  41.             </div>  
  42.         </div>  
  43.    
  44.         <div class="form-group">  
  45.             @Html.LabelFor(model => model.Position, htmlAttributes: new { @class = "control-label col-md-2" })  
  46.             <div class="col-md-10">  
  47.                 @Html.EditorFor(model => model.Position, new { htmlAttributes = new { @class = "form-control" } })  
  48.                 @Html.ValidationMessageFor(model => model.Position, ""new { @class = "text-danger" })  
  49.             </div>  
  50.         </div>  
  51.    
  52.         <div class="form-group">  
  53.             @Html.LabelFor(model => model.Office, htmlAttributes: new { @class = "control-label col-md-2" })  
  54.             <div class="col-md-10">  
  55.                 @Html.EditorFor(model => model.Office, new { htmlAttributes = new { @class = "form-control" } })  
  56.                 @Html.ValidationMessageFor(model => model.Office, ""new { @class = "text-danger" })  
  57.             </div>  
  58.         </div>  
  59.    
  60.         <div class="form-group">  
  61.             @Html.LabelFor(model => model.HireDate, htmlAttributes: new { @class = "control-label col-md-2" })  
  62.             <div class="col-md-10">  
  63.                 @Html.EditorFor(model => model.HireDate, new { htmlAttributes = new { @class = "form-control" } })  
  64.                 @Html.ValidationMessageFor(model => model.HireDate, ""new { @class = "text-danger" })  
  65.             </div>  
  66.         </div>  
  67.    
  68.         <div class="form-group">  
  69.             @Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })  
  70.             <div class="col-md-10">  
  71.                 @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })  
  72.                 @Html.ValidationMessageFor(model => model.Salary, ""new { @class = "text-danger" })  
  73.             </div>  
  74.         </div>  
  75.    
  76.         <div class="form-group">  
  77.             <div class="col-md-offset-2 col-md-10">  
  78.                 <input type="submit" value="Create" class="btn btn-default" />  
  79.             </div>  
  80.         </div>  
  81.     </div>  
  82. }  
  83.    
  84. <div>  
  85.     @Html.ActionLink("Back to List""Index")  
  86. </div>

Step 7

Build and run the project by pressing Ctrl+F5.

The question is do we really have to write all the dirty code of retrieving data from FormCollection class and assign it to the properties of “employee” object? The answer is no. This is the job of the model binder in MVC. 

FormCollection In ASP.NET MVC


Similar Articles