DEV Community

Cover image for What is Form Collection and how to implement it in ASP .NET MVC?
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

What is Form Collection and how to implement it in ASP .NET MVC?

What is Form Collection?

Form collection is used to retrieve input elements from the controller action method. Form collection class automatically receives the data form value in controller methods in the form of key/value pair. Key and value pairs are accessed using the key name and index value.

How to Implement form collection in ASP.NET MVC?

Here in this article, I will show you how to use form collection and how we can use form collection class.

Here I will create the view to enter data into a database table using the form collection class available in ASP.NET MVC.

STEP 1
Open Visual Studio or any editor and create a new Asp.net Web Application (.NET Framework) application and provide the appropriate name.

Image description
[Fig:- Create project]

STEP 2
Select MVC Option or either use the Empty template as per your choice.

Image description
[Fig:- MVC Application]

STEP 3

Now, we need to enter the data model into our application. Right-click on a model folder and then click Add. Select Ado.NET Entity Data Model. If the Data model does not show this way you can click on a new item and select ADO.NET Entity Data Model.

Image description
[Fig:- ADO.NET Entity Data Model]

Give the name for the Entity model

Image description
[Fig:- ADO.NET Entity Data Model Name]

After Clicking OK. This wizard will open select EF Designer from Database. Here I will use the database first approach so I will choose EF Designer first model that you can use any model according to your need but the above step is different from code first and models first approach.

Image description
[Fig:- EF Designer First model]

Read More: What Is Tempdata And How To Use In Mvc?

After clicking Next, a window will appear. Click New Connection. Another window will appear to add your server name and select your database and click OK.

Image description
[Fig:- New Connection]

Now a new connection will be added. Click OK.

Image description
[Fig:- New Connection string added ]

After clicking on Next you will select Entity Framework 6.0 and then click Next. Select a table according to your needs click on Finish.

After clicking on Finish your table will be added and the following classes will be added to your model folder.

Image description
[Fig:- Model folder]

STEP 4

Now we need to add a controller. Right-click on the controller folder and select MVC Empty controller click on Add.

After clicking in Add, another window will appear. Provide the name of the controller and click Add. Your Controller will be added to the controller folder.

Image description
[Fig:- MVC Empty Controller]

The form collection class automatically receives the form value in the controller action method in the form of key and value pair. Keys and value pairs can be accessed using a name or index.

We can use the loop to access each key and its value sent to the server. Let's add the following method.


using System;
using System.Collections.Generic;
using System. Linq;
using System. Web;
using System.Web.Mvc;
using FromCollectionDemo.Models;

namespace FromCollectionDemo.Controllers
{
    public class EmployeeController: Controller
    {
        Trainee2021Entities db = new Trainee2021Entities();
        // GET: Employee
        public ActionResult Index()
        {
            var employee = db.employees.ToList();
            return View(employee);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(FormCollection formCollection)
        {
            if (ModelState.IsValid)
            {
                foreach (string key in formCollection.AllKeys)
                {
                    Response.Write("Key=" + key + " ");
                    Response.Write("Value=" + formCollection[key]);
                    Response.Write("
");
                }

            }
            return View();
        }
    }

Enter fullscreen mode Exit fullscreen mode

Looking for Trusted .Net Development Company? Your Search ends here.

If you run this code inside the EmployeeController you will get the following output on your screen.

Image description
[Fig:- key Value pair]

The above code does not insert the data in the database it simply displays our data in key-value pair. But I want to enter data into the database so I want to change my code. Here is my full code for EmployeeController

EmployeeController


using System;
using System.Collections.Generic;
using System. Linq;
using System. Web;
using System.Web.Mvc;
using FromCollectionDemo.Models;

namespace FromCollectionDemo.Controllers
{
    public class EmployeeController: Controller
    {
        Trainee2021Entities db = new Trainee2021Entities();
        public ActionResult Index()
        {
            var employee = db.employees.ToList();
            return View(employee);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(FormCollection formCollection)
        {
            if (ModelState.IsValid)
            {
                employee emp = new employee();
                emp.Firstname = formCollection["Firstname"];
                emp.Lastname = formCollection["Lastname"];
                emp.Gender = formCollection["Gender"];
                emp.Salary = Convert.ToInt32(formCollection["Salary"]);
                emp.State = formCollection["State"];
                emp.Address = formCollection["Address"];
                db.employees.Add(emp);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View();
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

STEP 5

Right click on the Index method in Employee controller. Click on Add View the window will appear select List template and model class.

After clicking the Add. it will create an Index view page on the Index page where we get a list of records from the database.

Image description
[Fig:- Index view]

In the same way, we can create a view for Create method but we select Create Template it will generate the default code.

Run the Create. Cshtml, it gives the following output

Image description
[Fig:- Create Page]

For Gender it has a radio button and also for State is ideal for a drop-down list instead of a text box. To achieve this functionality, I change my code. Here is my full code for Create View.

Now use the code and you will get the next result.

Create.cshtml


  @model FromCollectionDemo.Models.employee

  @{
      ViewBag.Title = "Create";
  }<h2>Create</h2>
  @using (Html.BeginForm()) { @Html.AntiForgeryToken()
<div class="form-horizontal"><h4>employee</h4>
<hr><div class="form-group">@Html.LabelFor(model => model.Firstname, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Firstname, new { htmlAttributes = new { @class = "form-control" } })</div></div>
<div class="form-group">@Html.LabelFor(model => model.Lastname, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Lastname, new { htmlAttributes = new { @class = "form-control" } })</div></div>
<div class="form-group">@Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })</div></div>
<div class="form-group">@Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">Male @Html.RadioButtonFor(model => model.Gender, "Male") Female @Html.RadioButtonFor(model => model.Gender, "Female")</div></div>
<div class="form-group">@Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.DropDownList("State" , new List<selectlistitem> { new SelectListItem{Text = "Gujarat" , Value="Gujarat"}, new SelectListItem { Text = "Mumbai" , Value ="Mumbai"}, new SelectListItem{ Text ="Delhi" ,Value = "Delhi"}, new SelectListItem{ Text ="Hydrabad" ,Value = "Hydrabad"} },"select State" ,new {@class ="form-control"}) </selectlistitem></div></div>
<div class="form-group">@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })</div></div>
<div class="form-group"><div class="col-md-offset-2 col-md-10"><input class="btn btn-default" type="submit" value="Create"></div></div></div>
  }
<div>@Html.ActionLink("Back to List", "Index")</div>
  @section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Enter fullscreen mode Exit fullscreen mode

Now run the code and you will get the following output.

Image description
[Fig:- Create Page ]

Image description
[Fig:- Index Page]

Conclusion

In this article, we have learned Form Collection automatically retrieves input element value from a controller action method. Use the form collection class to retrieve input element data.

Top comments (0)