FormCollection Object in ASP.NET MVC with Example

In this chapter, you will learn:
1. What is FormCollection Object
2. Retrieving Form Data using FormCollection in MVC 5
3. FormCollection Object Programming Example

What is FormCollection Object?

A FormCollection Object is used to retrieve form input values in action method. In the previous chapter, I have explained 4 different ways to create form and gather form data in action method. FormCollection object makes programmers job easier and forms data can be easily accessed in action method.

FormCollection Example - Retrieving Form Data

Step 1: Create a New ASP.NET MVC Project or open Existing Project.
Step 2: Create a new Model StudentModel.cs and add the following code in it.
namespace MvcForms.Models
    public class StudentModel
        public int Id { get; set; }
        public string Name { get; set; }
        public bool Addon { get; set; }

Step 3: Go to Views Home Index.cshtml and add the following code to create form.
<h3><b>Forms - Form Collection Objects</b></h3>
@using (Html.BeginForm("Submit", "Home", FormMethod.Post))
            <td>Enter ID: </td>            
            <td>Enter Name: </td>
            <td>Addon: </td>
            <td>@Html.CheckBox("Addon", false)</td>
            <td colspan="2"><input type="submit" value="Submit"></td>
<h4 style="color:purple">
    ID: @ViewBag.Id<br />
    Name: @ViewBag.Name<br />
    Addon: @ViewBag.Addon

Step 4: Create following action method in HomeController
        public ActionResult Submit(FormCollection fc)
            ViewBag.Id = fc["Id"];
            ViewBag.Name = fc["Name"];
            bool chk = Convert.ToBoolean(fc["Addon"].Split(',')[0]);
            ViewBag.Addon = chk;

            return View("Index");

Step 5: Run your Project.
FormCollection Output
Let's understand this code
1. Created simple MVC Forms using HTML Helper
2. In Submit Action Method, I have initialized FormCollection object fc.
3. FormCollection value can be accessed either giving input control "id" or index number.
4. If you will not split Boolean value then you will get "true, false" both output, that's why I have gathered checkbox value in Boolean type variable and split them.
bool chk = Convert.ToBoolean(fc["Addon"].Split(',')[0]);


In this chapter, I tried to teach you FormCollection object with an easy and complete example. In the next chapter, you will learn Form Validation Techniques in ASP.NET MVC.


Share your thought