Introduction
In ASP.NET MVC, when we submit a form, we need to collect user input data and send it to the controller.
There are multiple ways:
π In this blog, we will learn everything step-by-step in easy words:
1. What is FormCollection?
FormCollection is a class in MVC used to get form values as key-value pairs.
π It works like:
Name = Abhay
Age = 25
City = Ahmedabad
All values come in string format.
2. Why We Use FormCollection?
We use FormCollection when:
β οΈ Not recommended for large projects (use Model instead)
3. Create Form in MVC (View)
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { id = "myForm" }))
{
<div>
Name: <input type="text" name="Name" />
</div>
<div>
Age: <input type="text" name="Age" />
</div>
<div>
City: <input type="text" name="City" />
</div>
<button type="submit">Submit</button>
}
Important
π name attribute is VERY IMPORTANT
Controller uses this name to get value
4. Controller (Using FormCollection)
[HttpPost]
public ActionResult Create(FormCollection form)
{
string name = form["Name"];
string age = form["Age"];
string city = form["City"];
return View();
}
Explanation
5. Convert Data Types
int age = Convert.ToInt32(form["Age"]);
6. Save Data in SQL Server using Model
Model
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
Controller (Save Data)
[HttpPost]
public ActionResult Create(FormCollection form)
{
Student obj = new Student();
obj.Name = form["Name"];
obj.Age = Convert.ToInt32(form["Age"]);
obj.City = form["City"];
using (MyDbContext db = new MyDbContext())
{
db.Students.Add(obj);
db.SaveChanges();
}
return RedirectToAction("Index");
}
Explanation
7. jQuery with Form Submit (AJAX)
jQuery Code
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$("#myForm").submit(function (e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: '/Home/Create',
type: 'POST',
data: formData,
success: function () {
alert("Data Saved Successfully");
}
});
});
</script>
Explanation
.serialize() β convert form into key-value
AJAX sends data without page reload
Controller receives same as normal form
8. Using FormCollection with Checkbox
var skills = form.GetValues("SelectedSkills");
9. Using FormCollection with Radio Button
var gender = form["Gender"];
10. FormCollection vs Model Binding
Feature
FormCollection
Model Binding
Type Safety
β No
β
Yes
Easy to Use
β Medium
β
Easy
Large Form
β Not Good
β
Best
Validation
β Manual
β
Automatic
11. Important Points
β Always match name with key
β Convert data types manually
β Use Model for real projects
β Use AJAX for better UX
12. Common Mistakes
β Missing name attribute
β Wrong key in form[""]
β Not converting int values
β Not handling null values
13. Conclusion
FormCollection is useful for quick and dynamic form handling.
You learned: