Introduction
FormCollection is a way to get all form input values in Controller.
When user fills form and clicks submit
All data goes to Controller
We can access it using FormCollection
👉 Think like:
FormCollection = "bag of all form values"
Step 1: Create Simple Form (View)
@using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
{
<label>Name:</label>
<input type="text" name="Name" />
<br />
<label>Email:</label>
<input type="text" name="Email" />
<br />
<label>Age:</label>
<input type="number" name="Age" />
<br />
<input type="submit" value="Submit" />
}
What is this?
Step 2: Controller Code
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get data from form
string name = form["Name"];
string email = form["Email"];
string age = form["Age"];
// Just for testing (display data)
ViewBag.Message = "Name: " + name +
", Email: " + email +
", Age: " + age;
return View("Result");
}
Step 3: Show Data (Result View)
<h2>@ViewBag.Message</h2>
What is this?
Output Example
If user enters:
👉 Output:
Name: Abhay, Email: [email protected], Age: 22
Important Points (Very Easy)
1. Name attribute is VERY important
<input type="text" name="Name" />
What is this?
👉 Controller will use this:
form["Name"]
2. FormCollection stores data as Key-Value
👉 Example:
Name = Abhay
Email = [email protected]
3. Everything comes as string
👉 Even Age is string:
int age = Convert.ToInt32(form["Age"]);
Real Example with Convert
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
string name = form["Name"];
int age = Convert.ToInt32(form["Age"]);
return Content("Name: " + name + ", Age: " + age);
}
Disadvantages of FormCollection
Better Option (Recommended)
👉 Use Model Binding instead of FormCollection
public ActionResult SaveData(Student model)
{
string name = model.Name;
}
When to Use FormCollection
Small forms
Quick testing
When model not required
Simple Real-Life Example
👉 Think:
Form = Shopping form
FormCollection = Basket
Each item = Key-Value
Conclusion
FormCollection is:
Easy
Fast
Beginner-friendly
But for real projects → use Model